Meaning of Java @Override
found here: http://stackoverflow.com/questions/4736212/meaning-of-android-override
@Override is a Java annotation. It tells the compiler that the following method overrides a method of itssuperclass. For instance, say you implement a Person class.
public class Person {
public final String firstName;
public final String lastName;
//some methods
@Override public boolean equals(Object other) {
...
}
}
The person class has an equals() method. The equals method is already defined in Person's superclassObject. Therefore the above implementation of equals() is a redefinition of equals() for Persons. That is to say, Person overrides equals().
It is legal to override methods without explicitly annotating it. So what is the @Override annotation good for? What if you accidentally tried to override equals() that way:
public boolean equals(Person other) {
...
}
The above case has a bug. You meant to override equals() but you didn't. Why? because the real equals() gets an Object as a parameter and your equals() gets a Person as a parameter. The compiler is not going to tell you about the bug because the compiler doesn't know you wanted to override. As far as the compiler can tell, you actually meant to overload equals(). But if you tried to override equals using the @Override annotation:
@Override public boolean equals(Person other) {
...
}
Now the compiler knows that you have an error. You wanted to override but you didn't. So the reason to use the @Override annotation is to explicitly declare method overriding
No comments:
Post a Comment