As far as I understand, this can be used inside a class to call a method available in any of its superclass as the compiler will look for the method in its superclasses if it's not available in the (sub)class. Basically just like using a super.
So I was wondering, which is the better way of doing things? Is there a general rule of thumb for sing either?
QUESTION:
When the method in question is not coded i.e only available via inheritance from its super class) in the (sub)class, they basically do the same thing right? In that case, is there a reason to pick one over the other?
super.methodAvailableInSuper();
or
this.methodAvailableInSuper();
MORE CLARIFICATION
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
They're not equivalent, so your question isn't meaningful.
this.method() will invoke the most-derived override of method(), including in any derived classes that this object may be an instance of
super.method() will invoke the base class's implementation of method(), or whatever implementation it inherited if it doesn't provide an implementation itself.
You should use whichever one does exactly what you want. It's not just an aesthetic choice, or a question of 'good practice'.
EDIT Re your edited edit:
When the method in question is not available in base class, they basically do the same thing right?
Wrong. super always calls a method in the base class or one of its parents. this calls the most-derived override. You would write super if you definitely didn't want to call any future implementation in any future derived class, and you would write this, or nothing, if you did want to call such an implementation if it exists when the call is made. Which is not something you can know when coding.
This is not a question of "best practice" since these keywords are very different.
When you call super.methodAvailableInSuper(); then all parent classes are searched for this method at runtime. If this method exists in the current class or any subclass, this method wont be executed.
You can use this, if you want to call the super implementation of an overriden method without cousing an endless loop.
The keyword this calls the method on the current object. Thus the normal execution of methods will be performed.
See also:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
This question already has answers here:
When do you use Java's #Override annotation and why?
(27 answers)
Closed 9 years ago.
Let's say I have this method in my runnable.
I always delete that #override. But I want to know if there is any negative effects to this?
I tried to search but didnt find nothing.
#Override
public void run() {
while (running) {
}
}
The #Override annotation does not make any difference to your production code. In fact, the annotation is not even encoded in the java byte code of your class, this is stated on the definition of the annotation:
#Target(value=METHOD)
#Retention(value=SOURCE)
public #interface Override
It's only retained in the source code.
So what's the point? Well it's something that's checked at compile-time. This allows you to state that you are intentionally overriding a method in a super-class.
You'll notice that if you add the #Override annotation to a method that is not overriding a parent method, then you'll get a compilation error.
The idea behind this is that if you are extending a class from a third-party library, and overriding one of it's methods, then you need to be warned if that method no longer exists. Consider upgrading the version of the external library you're using, and instead of void run() the method was now void run(String threadName).
In that case, your overridden method would never get invoked, as it no longer overrides the parent method (not the best of examples, as you're implementing an interface - so compilation would fail anyway, but imagine if it was a class).
This annotation can be set when you override methods from classes, as well as interfaces (although this is only supported in Java 1.6 and above).
Functionally, there is no difference.
However, with the annotation, you get the added checks that there is a run() method to override, which can catch bugs where you aren't using the interface you think you are using.
If you add the clause, you are telling the compiler implicitly that you are overriding a method from a super type, which leads to make it check for a method with the same name from the superclass. This means that if you misspelled something or the method doesn't have the same return type, the compiler will tell you.
You can, but this will disable the compile-time check and makes it less readable.
Since it doesn`t cost you anything to leave it as it is, you should not spend any effort with deleting the annotation.
This is a question about coding style and recommended practices:
As explained in the answers to the question unnecessary to put super() in constructor?, if you write a constructor for a class that is supposed to use the default (no-arg) constructor from the superclass, you may call super() at the beginning of your constructor:
public MyClass(int parm){
super(); // leaving this out makes no difference
// do stuff...
}
but you can also omit the call; the compiler will in both cases act as if the super() call were there.
So then, do you put the call into your constructors or not?
On the one hand, one might argue that including the super() makes things more explicit. OTOH, I always dislike writing redundant code, so personally I tend to leave it out; I do however regularly see it in code from others.
What are your experiences? Did you have problems with one or the other approach? Do you have coding guidelines which prescribe one approach?
BTW: A related question (just for reference):
Is there a reason to explicitly code a default constructor when there are no other constructors?
I don't write the super() call for the same reason I don't write unnecessary casts:
It adds noise to the code without providing any additional information (neither to the compiler nor to the developer reading my code).
The default settings of some versions of some IDEs generate it automatically, so that's one reason you might be seeing it.
Whether to write it or not depends on who will be reading it. I prefer not to add it, but if you are not certain that team members understand what the compiler does, and how object construction proceeds, you may add it "just in case".
I don't, but the argument given to me for doing this while at university was that it makes things more explicit, so you don't 'forget' that a superclass constructor is being called.
I just don't see the need tho.
I use the super() only when the constructor super() needs parameters.
What are your experiences? Did you
have problems with one or the other
approach?
I never called the default constructor (explicit) and never faced any problems
I never add it and I was deeply shocked when a colleague didn't understand that there was an implicit call made to the super class so perhaps I should start doing it.
Advantage: Anyone reading your code knows that you really want to call the default constructor, you did not leave the call out by mistake.
Disadvantage: You clutter your code with unimportant information.
Usually, if a language lets you omit some instruction, it is not bad style doing so. I think it is a question of weighing the pros and cons. For instance, explicitly writing super() when your constructor has parameters and the base class also has parametered constructors available may be a good idea.
I actually put the super() call in as I find it to be a helpful memory aide. When I have written a piece of code a few months ago and return to it, the super() reminds me when I am looking at the constructor that the class I wrote inherits from something.
I try to avoid writing code where calling super() is necessary, because I prefer composition over inheritance.
If I have to derive from another class, I try to put both behind an own interface and pass one of them to the other as a dependency.
If I have a lib class, however, which I cannot give an extra dependency, the first thing I try is to use a decorator.
If this doesn't work, and I have to derive from an implementation, I think it doesn't matter whether to write super() or not, since it happens so rarely ;)
So, all in all, I think this question is pointless.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When do you use Java’s #Override annotation and why?
Is there any reason to annotate a method with #Override other than to have the compiler check that the superclass has that method?
As you describe, #Override creates a compile-time check that a method is being overridden. This is very useful to make sure you do not have a silly signature issue when trying to override.
For example, I have seen the following error:
public class Foo {
private String id;
public boolean equals(Foo f) { return id.equals(f.id);}
}
This class compiles as written, but adding the #Override tag to the equals method will cause a compilation error as it does not override the equals method on Object. This is a simple error, but it can escape the eye of even a seasoned developer
It not only makes the compiler check - although that would be enough to make it useful; it also documents the developer's intention.
For instance, if you override a method but don't use it anywhere from the type itself, someone coming to the code later may wonder why on earth it's there. The annotation explains its purpose.
Nope, you pretty much nailed it.
#Override tells the compiler your intent: if you tag a method #Override, you intended to override something from the superclass (or interface, in Java 6). A good IDE will helpfully flag any method that overrides a method without #Override, so the combination of the two will help ensure that you're doing what you're trying to.
nope -- except that it also improves readability (i.e. in addition to whatever indicator your IDE uses, it makes it easy to spot that a method overrides a declaration in the superclass)
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What are the best practices for using Java's #Override annotation and why?
It seems like it would be overkill to mark every single overridden method with the #Override annotation. Are there certain programming situations that call for using the #Override and others that should never use the #Override?
Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like #Implements), but it's better than nothing.
I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
protected boolean displaySensitiveInformation() {
return false;
}
You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.
Suppose this method is changed in the parent class to
protected boolean displaySensitiveInformation(Context context) {
return true;
}
This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.
To answer your question: you should use the #Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.
There are many good answers here, so let me offer another way to look at it...
There is no overkill when you are coding. It doesn't cost you anything to type #override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.
Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing #override for the rest of your life; but one error it prevents can save you hours.
Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.
Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?
Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.
I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.
It will catch things like tostring() instead of toString()
The little things help in large projects.
Using the #Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.
The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The #Override annotation safeguards against this.
To take advantage from compiler checking you should always use Override annotation. But don’t forget that Java Compiler 1.5 will not allow this annotation when overriding interface methods. You just can use it to override class methods (abstract, or not).
Some IDEs, as Eclipse, even configured with Java 1.6 runtime or higher, they maintain compliance with Java 1.5 and don’t allow the use #override as described above. To avoid that behaviour you must go to: Project Properties ->Java Compiler -> Check “Enable Project Specific Settings” -> Choose “Compiler Compliance Level” = 6.0, or higher.
I like to use this annotation every time I am overriding a method independently, if the base is an interface, or class.
This helps you avoiding some typical errors, as when you are thinking that you are overriding an event handler and then you see nothing happening. Imagine you want to add an event listener to some UI component:
someUIComponent.addMouseListener(new MouseAdapter(){
public void mouseEntered() {
...do something...
}
});
The above code compiles and run, but if you move the mouse inside someUIComponent the “do something” code will note run, because actually you are not overriding the base method mouseEntered(MouseEvent ev). You just create a new parameter-less method mouseEntered(). Instead of that code, if you have used the #Override annotation you have seen a compile error and you have not been wasting time thinking why your event handler was not running.
#Override on interface implementation is inconsistent since there is no such thing as "overriding an interface" in java.
#Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway.
There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.
#Override on interface implementers should never have been permitted in 1.6, and with eclipse sadly choosing to auto-insert the annotations as default behavior, we get a lot of cluttered source files. When reading 1.6 code, you cannot see from the #Override annotation if a method actually overrides a method in the superclass or just implements an interface.
Using #Override when actually overriding a method in a superclass is fine.
Its best to use it for every method intended as an override, and Java 6+, every method intended as an implementation of an interface.
First, it catches misspellings like "hashcode()" instead of "hashCode()" at compile-time. It can be baffling to debug why the result of your method doesn't seem to match your code when the real cause is that your code is never invoked.
Also, if a superclass changes a method signature, overrides of the older signature can be "orphaned", left behind as confusing dead code. The #Override annotation will help you identify these orphans so that they can be modified to match the new signature.
If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.
Using #Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).
#Override on interfaces actually are helpful, because you will get warnings if you change the interface.
Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.
Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.
It makes absolutely no sense to use #Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.
Whenever a method overrides another method, or a method implements a signature in an interface.
The #Override annotation assures you that you did in fact override something. Without the annotation you risk a misspelling or a difference in parameter types and number.
I use it every time. It's more information that I can use to quickly figure out what is going on when I revisit the code in a year and I've forgotten what I was thinking the first time.
The best practive is to always use it (or have the IDE fill them for you)
#Override usefulness is to detect changes in parent classes which has not been reported down the hierarchy.
Without it, you can change a method signature and forget to alter its overrides, with #Override, the compiler will catch it for you.
That kind of safety net is always good to have.
I use it everywhere.
On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.
I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.
Used only on method declarations.
Indicates that the annotated method
declaration overrides a declaration
in supertype.
If used consistently, it protects you from a large class of nefarious bugs.
Use #Override annotation to avoid these bugs:
(Spot the bug in the following code:)
public class Bigram {
private final char first;
private final char second;
public Bigram(char first, char second) {
this.first = first;
this.second = second;
}
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
public int hashCode() {
return 31 * first + second;
}
public static void main(String[] args) {
Set<Bigram> s = new HashSet<Bigram>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new Bigram(ch, ch));
System.out.println(s.size());
}
}
source: Effective Java
Be careful when you use Override, because you can't do reverse engineer in starUML afterwards; make the uml first.
It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing #Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use #Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.
Of course, this scenario is mostly hyperbole; the derived class would no longer compile, now lacking an implementation of the renamed interface method, and today one would likely use a Rename Method refactoring operation to address the entire code base en masse.
Given that IDEA's inspection is not configurable to ignore implemented interface methods, today I'll change both my habit and my team's code review criteria.
The annotation #Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.
BTW, if we didn't announce the annotation #Override in the subclass, but we do override some methods of the super, then the function can work as that one with the #Override. But this method can not notify the developer when the super's method was changed. Because it did not know the developer's purpose -- override super's method or define a new method?
So when we want to override that method to make use of the Polymorphism, we have better to add #Override above the method.
I use it as much as can to identify when a method is being overriden. If you look at the Scala programming language, they also have an override keyword. I find it useful.
It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.
Override annotation is used to take advantage of the compiler, for checking whether you actually are overriding a method from parent class. It is used to notify if you make any mistake like mistake of misspelling a method name, mistake of not correctly matching the parameters
i think it's best to code the #override whenever allowed. it helps for coding. however, to be noted, for ecipse Helios, either sdk 5 or 6, the #override annotation for implemented interface methods is allowed. as for Galileo, either 5 or 6, #override annotation is not allowed.
Annotations do provide meta data about the code to the Compiler and the annotation #Override is used in case of inheritance when we are overriding any method of base class. It just tells the compiler that you are overriding method. It can avoide some kinds common mistakes we can do like not following the proper signature of the method or mispelling in name of the method etc. So its a good practice to use #Override annotation.
For me the #Override ensures me I have the signature of the method correct. If I put in the annotation and the method is not correctly spelled, then the compiler complains letting me know something is wrong.
Simple–when you want to override a method present in your superclass, use #Override annotation to make a correct override. The compiler will warn you if you don't override it correctly.