Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








6.2 Annotating an Overriding Method


The Override annotation


type is a marker interface, and has no members
to initialize. It is used to indicate that a method is overriding a
method from its superclass. In particular, it's supposed to help ensure you
actually do override a methodby avoiding misspellings or confusion
over the correct name and parameter list of the method you're trying to
override. In these cases of error, a compiler can catch the problem and
report it.


6.2.1 How do I do that?


Because Override is a marker interface, there are no values that you need
to supply it. Just preface it with the annotation syntax marker, the at sign
(@), and type "Override". This should be on a line by itself, just before the
method declaration you want to indicate as an overriding method, as
seen in Example 6-1.

NOTE

Largely by coincidence,
the @ sign,
pronounced "at", is
a mnemonic for
Annotation Type.


Example 6-1. Using the Override annotation type

package com.oreilly.tiger.ch06;
public class OverrideTester {
public OverrideTester( ) { }
@Override
public String toString( ) {
return super.toString( ) + " [OverrideTester Implementation]";
}
@Override
public int hashCode( ) {
return toString( ).hashCode( );
}
}

This isn't very sexy or glamorous, but it compiles without any problem.
Where things start to become useful is when you don't do what you
intended do. Change the hashCode( ) method to look like this:

     @Override
public int hasCode( ) {
return toString( ).hashCode( );
}

NOTE

This method
exists, but is
commented out
of, the Override-
Tester's source
listing in the
book's sample
code.

Here, hashCode( ) is misspelled, and the method is no longer overriding
anything, making the annotation speak up. Compile this class, and you'll
get the following error:

       [javac] src\ch06\OverrideTester.java:1:
method does not override a method from its superclass
[javac] @Override
[javac] ^
[javac] 1 error

Suddenly, that little annotation becomes quite a boon, catching mistakes
at compile time. It's also such an easy thing to integrate into your programming
practices that I'd recommend you use it often.


6.2.2 What about...


...the methods that should be overridden? Override marks the overriding
method, not the overridden methodthis is an important distinction, and
you should learn it well. Java has ways to indicate that a method should
be overridden alreadynamely, by declaring that method as abstract.


/ 131