Question about #Override annotation - java

Im new to android development. I would like to know why do we have to precede every overriden method with #Override annotation in android ?. In regular java this is not a requirement.
Please Help
Thanks

The #Override notation is used so the compiler can warn you if the method-signature isn't the same as the super class method-signature. It can warn you about tedious bugs, and it is not required in Android, but it is good practice both in "normal" Java programming and Android Programming.
If you in "normal" Java had misspelled the toString-method e.g. public String toString(int n) {...} and you had the #Override the compiler will warn you because you are not overriding a method in the superclass.

It's a best practice and it's safe. Assume that you have a class:
public class MyClass {
...
...
public void doSomething() {
...
...
}
}
Now assume you extend it:
public class MyExtendedClass extends MyClass {
...
...
public void doSomthing() {
...
}
}
This code will compile, but you'll have problems because you actually haven't overridden the method! Note the misspelling. Now if you annotate it with #Override:
public class MyExtendedClass extends MyClass {
...
...
#Override
public void doSomthing() {
...
}
}
The java compiler will complain because you are trying to override a method that does not exist in the base class. Essentially using #Override lets you catch problems like these at compile-time.
This is especially useful when you refactor. If you change a method signature or a name, but don't have the #Override annotation, some methods may slip-by leading to hard-to-find bugs (of course, with modern IDE's a lot of this pain is mitigated, but still). If you judiciously use the #Override annotation, you will now get compiler errors and so you will be able to fix the method signatures in your derived classes.

Because it is a good programming practice. Overriding a method without using #Override makes for a potentially difficult-to-find bug in the future if the base method's signature changes (I've wasted hours on these sorts of bugs before).

Related

Why in both the code snippets '#Override' annotation work properly?

Although the class B implements the interface A, it does not provide the implementation of the method show(). Again, D extends C but in class D the implementation of displayNothing() is the same as the implementation of displayNothing() method in its superclass C.
But in both the cases #Override annotation work properly, why?
//code snippet 1
interface A
{
void show();
}
abstract class B implements A
{
#Override
abstract public void show();
}
//code snippet 2
class C
{
void displayNothing()
{
}
}
class D extends C
{
#Override
void displayNothing()
{
}
}
#Override is only bothered with whether your function name along with the data type is just the same as the method in your super class (with no Alphabetical error). In your case it is the same.Try changing void as int in your class D. It shows a compilation error. As for your abstract class method, it needn't define anything coz the name says it all, it is abstract.
The purpose of the #Override annotation is to prevent bugs. It's presence informs the compiler that there must be a inherited method with that same exact signature that this class is overriding. It does matter if there is an implementation of a method or not.
It is perfectly legal to not include an #Override annotation. The potential problem you might encounter, though, is if you accidentally had a typo or inadvertently changed the method signature, you would be overloading the method, not overriding it. The compiler would not be able to catch this bug. The program might crash or it might even run, but run incorrectly.
Because this might be a difficult bug to spot, especially with methods containing several parameters, the #Override annotation was created. The #Override annotation informs the compiler that this method is an override, not an overload and if the compiler fails to find a method to override, return a compilation error.
All these methods would compile and could be run but none would override the displayNothing() method.
void displayNothng();
void displaynothing();
void displayNothing(String value);
The #Override annotation "works properly" in both presented cases, because java reuses this annotation for interfaces and classes, even if you feel that the first and the second snippet of code do something different it's just not as important to introduce separated keywords/annotations to differentiate between overriding from an interface and from a class. Even an abstract class doesn't change things here.
The #Override indicates that a given method has a compatible representation in the super class/interface, it's used to ensure we don't have any syntax issue in the definition.
B is abstract. Abstract classes don’t need to provide implementations. If an abstract class doesn’t implement a required method it doesn’t matter. If a class isn’t abstract, then implementations of all abstract methods need to be there.
D provides an override of the displayNothing method in C. The compiler doesn’t check whether the overridden version is the same as the overriding version, and it doesn't care if the overriding implementation is empty. All the Override annotation does is confirm that there is a method with the same signature above the annotated one in the class hierarchy.
The purpose of the annotation is to confirm that you’re actually overriding an existing method and haven’t introduced a bug by misspelling the method name or otherwise not matching the signature of the method you mean to override. See the Java Language Specification, 9.6.4.4, where it says:
Programmers occasionally overload a method declaration when they mean to override it, leading to subtle problems. The annotation type Override supports early detection of such problems.
The classic example concerns the equals method. Programmers write the following in class Foo:
public boolean equals(Foo that) { ... }
when they mean to write:
public boolean equals(Object that) { ... }
This is perfectly legal, but class Foo inherits the equals implementation from Object, which can cause some very subtle bugs.
(Be aware when I describe what #Override does I'm skipping over override-equivalence because you didn't ask about it and there are already perfectly good answers that cover that.

Why the constant use of #Override in android programming? [duplicate]

In java or Android there are #Override annotations. What does it mean? I found that it is used when method is from subclass or inherited interface's method, I want to know further and other is #SuppressWarnings its also Anonation, if yes how many annonation used by java and for which purpose.
This question is also answered here, and quite succinctly:
Android #Override usage
It's an annotation that you can use to tell the compiler and your IDE that you intend the method that has that annotation to be an override of a super class method. They have warning/errors in case you make mistakes, for example if you intend to override a method but misspell it, if the annotation is there the IDE or the compiler will tell you that it is not in fact overriding the super class method and thus you can determine why and correct the misspelling.
This is all the more important for Android applications and activities for example, where all of the calls will be based on the activity lifecycle - and if you do not properly override the lifecycle methods they will never get called by the framework. Everything will compile fine, but your app will not work the way you intend it to. If you add the annotation, you'll get an error.
In other words, if you add #Override this helps you make sure you are really overriding an existing method! Pretty darn useful.
Overriding means that you are changing the behavior of a method inherited from a parent class, without changing the signature. The #Override annotation is used to mark this. It is strongly linked with the concept of polymorphism. Example:
public class A {
public void foo() {
System.out.println("A");
}
}
public class B extends A {
#Override
public void foo() { // I want to change the way foo behaves
System.out.println("B"); // I want to print B instead of A
}
}
public static void main(String[] args) {
A a = new A();
a.foo(); // prints A
A b = new B(); // I can use type B because it extends A
b.foo(); // I have overriden foo so it prints B now
}
Just to ensure that you are actually overriding it at compile time, and to improve readability
Example:
class Animal{
public void eat(Food food){
}
}
class Person extends Animal {
#Override
public void eat(String food){
}
}
This will give you compile time error since you are not actually overriding it (see the type of food)
#override its an annotation i.e meta data introduce in jdk 1.6 . If you don't write it before override method , it won't make any difference but it just use to increase the readability of compiler.
To mark that you really implement or change a method. Like meantined it's checked at compile time. That is you for instance you get an error if you want to implement #Override public void equals(final Car pObject); instead of #Override public void equals(final Object pObject);.
Just go the source for the definition of both annotations, besides other additional details: the #Override and the #SuppressWarnings from the Java specs.
It sounds like your question is more about annotations in general, so I'll answer that. Annotations provide extra meta data about the item that is being annotated. This allows other code to use that information to decide how to run. More detailed description. There are a large number build into the language, but you can write your own.
The two examples you gave tell the compiler extra information about the code it is compiling. When it sees #Override, it checks to ensure that the method is actually overriding a method. When it sees #SuppressWarnings, it know that it should ignore any compiler warnings, of the given type, that exist inside the block of code.
They can be used outside of compilers as well. There are a number of libraries that have you annotate a class object and it uses that meta data to build a database or parse an xml file.

How to rectify? -- "both define getObjectCopy(), but with unrelated return types" -- but it's *one* function

I have the following interface heirarchy (with all non-relevant functions stripped out). I am getting this error when trying to compile it:
types ValidLineGettable and ValidateValue<java.lang.String> are incompatible; both define getObjectCopy(), but with unrelated return types
This is all derived from the same function--not two different functions with the same name, the same function in the same interface. How do you deal with interfaces that must inherit from two different interfaces that themselves must inherit from a singular base interface?
There are two SO questions I've found regarding different functions that happen to have the same name
Inherit method with unrelated return types
Java - Method name collision in interface implementation
In my case it's the same function, both conceptually and in name.
(Although I am interested in opinions on if the Copyable interface is a good idea to begin with...it's in a lot of code that I use, and has worked well for me...I am mostly interested in the general inheritance/design question.)
I am not clear on how to best deal with this. I would appreciate any advice. Thank you.
public interface Copyable {
Copyable getObjectCopy();
}
interface ValidateValue<O> extends Copyable {
//Other functions...
#Override
ValidateValue<O> getObjectCopy();
}
//For classes that may be able to be Decorated into a TextLineValidator
interface ValidLineGettable extends Copyable {
//Other functions...
ValidLineGettable getObjectCopy();
}
interface TextLineValidator extends ValidateValue<String>, ValidLineGettable {
//Other functions...
#Override
TextLineValidator getObjectCopy();
}
The error:
C:\java_code\Copyable.java:17: types ValidLineGettable and ValidateValue<java.lang.String> are incompatible; both define getObjectCopy(), but with unrelated return types
interface TextLineValidator extends ValidateValue<String>, ValidLineGettable {
^
1 error
Tool completed with exit code 1
Assuming all the return values extend Copyable, have all versions of getObjectCopy() return Copyable. For example:
public interface ValidateValue<O> extends Copyable
{
// Other functions...
#Override
Copyable getObjectCopy();
}
public Blammy implements ValidateValue<String>
{
// Other functions...
#Override
public Copyable getObjectCopy()
{
SomethingThatExtendsCopyable blammy = new SomethingThatExtendsCopyable();
return (Copyable)blammy;
}
}
Edit
In your code above the error is caused by the fact that the "getObjectCopy" method has a different return value in the ValidateValue<String> and ValidLineGettable interfaces, but the calling signature is the same. In java, you do not get polymorphism by changing only the return value; this results in a compile error.
If you change the return value to Copyable then the TextLineValidator no longer gains value by extending both of its parent interfaces. A simpler approach is to have one interface (Copyable) and multiple classes that implement that interface, each of which returns a Copyable value which may be an instance of a class that extends (or implements) Copyable.
The Eclipse compiler compiles your code without errors. JavaC from JDK 7 (1.7.0_45) and JDK 8 (1.8.0-ea) also work.
I think this is a bug in the JDK, most likely one related to bug #122881 (please note this one is fixed). I also found an issue in Google Protocol Buffer that points to another bug, but I can't find that one.
You could compile it with Eclipse or JDK 7, or change the code so that it doesn't require this feature.

Can't call supertype constructor directly - why not?

I have the following example classes in Java:
public class A { }
public class Super {
protected Super() { }
public Super(A a) { }
}
public class Sub extends Super { }
public class Consumer {
public Consumer() {
Sub sub = new Sub(new A()); //compiler error
}
}
The compiler error states that the arguments cannot be applied to the default constructor in Sub, which is perfectly understandable.
What I'm curious about is the rationale behind this decision. Java generates the default empty constructor in Sub; why can't it call it behind the scenes in this case? Is this primarily a case of sane hand-holding, or is there a technical reason?
EDIT
I'm aware that this is a language limitation. I'm curious about why it is a language limitation.
EDIT 2
It seems that, as is often the case, I was too close to the code I was actually working in to see the big picture. I've posted a counter-example in the answers below that shows why this is a Bad Thing®.
I think it's an issue of both readibility and not assuming intent. You say
Java generates the default empty constructor; why can't it call it behind the scenes in this case?
Yet to me, it would make much more sense for Java to implicitly call the Super(A) constructor "behind the scenes" than to call the Super() constructor, disregarding A.
And there you have it. We already have two disparate assumptions about what should (or could) happen in this case.
One of the Java language's core principles is transparency. As much as possible, the programmer should be able to see by looking at the code what will happen, sometimes at the expense of convenience or magic at the syntax level.
A parallel tenet to that is not assuming intent: in cases where the programmer's intentions seem ambiguous, the Java language will sometimes favour a compile error rather than automatically chosing a default through some (arbitrary or otherwise) selection algorithm.
public class Sub extends Super { }
does not have the constructor Sub(A a), it only has the default constructor Sub().
Constructors are not inherited.
Base classes need to call super constructors in order to ensure an object is properly instantiated. For instance consider:
class Super {
final String field1;
public Super(String field1) {
this.field1 = field1;
}
...
}
class Base extends Super {
final String field2;
public Base(String field2) {
this.field2 = field2;
}
...
}
Does Base's constructor override the Super constructor? If so, then field1 is no longer guaranteed to be initialized, making inherited methods behave unexpectedly.
The moment you add a non-default constructor to the subclass then inherited constructors stop working. I think it'd be a confusing and rarely useful feature it was added to the language, although technically I can see no reason why it wouldn't be possible.
You've overidden the default public constructor, so there isn't anything to call.
So the class Sub is equivalent to
public class Sub extends Super
{
protected Sub(){}
public Sub(A a) { }
}
It would because its
Sane behaviour - Behaves as specified by the programmer, and it also follows the concept of inheritance in OOP languages
Following its C++ legacy
I'm putting this out as a technical reason for this behavior; I'm in agreement with several other answers that this could be semantically confusing.
Consider the following example:
public class A { }
public abstract class Super {
protected Super() {
// perform time consuming, destructive, or
// otherwise one-time operations
}
public Super(A a) {
this();
// perform A-related construction operations
}
}
public class Sub extends Super { }
public class Consumer {
public Consumer() {
Sub sub = new Sub(new A());
}
}
When the Sub is constructed, in this case the default constructor on Sub would be called, which would chain to the default constructor on Super (because that's the magic the language defines). Then, the call to Super(A) would invoke logic that is designed to be run once, at construction. This is obviously not what the developer intends.
Even without the this() call in the Super(A) constructor, the developer's intention cannot be determined; the constructors may be mutually exclusive for some reason.

#MustOverride annotation?

In .NET, one can specify a "mustoverride" attribute to a method in a particular superclass to ensure that subclasses override that particular method.
I was wondering whether anybody has a custom java annotation that could achieve the same effect. Essentially what i want is to push for subclasses to override a method in a superclass that itself has some logic that must be run-through. I dont want to use abstract methods or interfaces, because i want some common functionality to be run in the super method, but more-or-less produce a compiler warning/error denoting that derivative classes should override a given method.
I don't quite see why you would not want to use abstract modifier -- this is intended for forcing implementation by sub-class, and only need to be used for some methods, not all. Or maybe you are thinking of C++ style "pure abstract" classes?
But one other thing that many Java developers are not aware of is that it is also possible to override non-abstract methods and declare them abstract; like:
public abstract String toString(); // force re-definition
so that even though java.lang.Object already defines an implementation, you can force sub-classes to define it again.
Ignoring abstract methods, there is no such facility in Java. Perhaps its possible to create a compile-time annotation to force that behaviour (and I'm not convinced it is) but that's it.
The real kicker is "override a method in a superclass that itself has some logic that must be run through". If you override a method, the superclass's method won't be called unless you explicitly call it.
In these sort of situations I've tended to do something like:
abstract public class Worker implements Runnable {
#Override
public final void run() {
beforeWork();
doWork();
afterWork();
}
protected void beforeWork() { }
protected void afterWork() { }
abstract protected void doWork();
}
to force a particular logic structure over an interface's method. You could use this, for example, to count invocations without having to worry about whether the user calls super.run(), etc.
... and if declaring a base class abstract is not an option you can always throw an UnsupportedOperationException
class BaseClass {
void mustOverride() {
throw new UnsupportedOperationException("Must implement");
}
}
But this is not a compile-time check of course...
I'm not sure which attribute you're thinking about in .NET.
In VB you can apply the MustOverride modifier to a method, but that's just the equivalent to making the method abstract in Java. You don't need an attribute/annotation, as the concept is built into the languages. It's more than just applying metadata - there's also the crucial difference that an abstract method doesn't include any implementation itself.
If you do think there's such an attribute, please could you say which one you mean?
Android has a new annotation out as announced in the Google I/O 2015:
#callSuper
More details here:
http://tools.android.com/tech-docs/support-annotations
If you need some default behaviour, but for some reason it should not be used by specializations, like a implementation of a logic in a non abstract Adapter class just for easy of prototyping but which should not be used in production for instance, you could encapsulate that logic and log a warning that it is being used, without actually having to run it.
The base class constructor could check if the variable holding the logic points to the default one. (writing in very abstract terms as I think it should work on any language)
It would be something like this (uncompiled, untested and incomplete) Java (up to 7) example:
public interface SomeLogic {
void execute();
}
public class BaseClass {
//...private stuff and the logging framework of your preference...
private static final SomeLogic MUST_OVERRIDE = new SomeLogic() {
public void execute() {
//do some default naive stuff
}
};
protected SomeLogic getLogic() { return MUST_OVERRIDE; }
//the method that probably would be marked as MustOverride if the option existed in the language, maybe with another name as this exists in VB but with the same objective as the abstract keyword in Java
public void executeLogic() {
getLogic().execute();
}
public BaseClass() {
if (getLogic() == MUST_OVERRIDE) {
log.warn("Using default logic for the important SomeLogic.execute method, but it is not intended for production. Please override the getLogic to return a proper implementation ASAP");
}
}
}
public GoodSpecialization extends BaseClass {
public SomeLogic getLogic() {
//returns a proper implementation to do whatever was specified for the execute method
}
//do some other specialized stuff...
}
public BadSpecialization extends BaseClass {
//do lots of specialized stuff but doesn't override getLogic...
}
Some things could be different depending on the requirements, and clearly simpler, especially for languages with lambda expressions, but the basic idea would be the same.
Without the thing built in, there is always some way to emulate it, in this example you would get a runtime warning in a log file with a home-made-pattern-like-solution, that only your needs should point if it is enough or a more hardcore bytecode manipulation, ide plugin development or whatever wizardry is needed.
I've been thinking about this.
While I don't know of any way to require it with a compile error, you might try writing a custom PMD rule to raise a red-flag if your forgot to override.
There are already loads of PMD rules that do things like reminding you to implement HhashCode if you choose to override equals. Perhaps something could be done like that.
I've never done this before, so I'm not the one to write a tutorial, but a good place to start would be this link http://techtraits.com/programming/2011/11/05/custom-pmd-rules-using-xpath/ In this example, he basically creates a little warning if you decide to use a wildcard in an import package. Use it as a starting point to explore how PMD can analyze your source code, visit each member of a hierarchy, and identify where you forgot to implement a specific method.
Annotations are also a possibility, but you'd have to figure out your own way to implement the navigation through the class path. I believe PMD already handles this. Additionally, PMD has some really good integration with IDEs.
https://pmd.github.io/

Categories

Resources