Why should I write "#Override"? [duplicate] - java

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.

Related

what will happen we don't use #override annotation? [duplicate]

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.

Faking abstract methods using exceptions in Java

I've been asked this question and am frankly stumped:
Instead of writing abstract methods we could try to fake them with exceptions, like this:
public int someMethod(int someparameter) {
throws new RuntimeException("unimplemented");
}
What would be the purpose of doing this and can anyone provide an example of code for an abstract method that the above is trying to fake? Any help is greatly appreciated. Thank you.
I can think of one (possibly) valid use case: You have an abstract class, and a number of other classes throughout your project that extended it. (Or the abstract class is in an open-source library, so you have no idea what other classes throughout the universe might be extended from it.) Now, you find that it's useful to add new abstract methods to this class. But if you add abstract methods to the class, this breaks every other class that has already extended it, because those classes need to be changed to contain override for the new methods. So I can see how, in some cases, it might be considered more feasible to add them as non-abstract methods and have them throw exceptions just in case a new class that extends it uses the new methods but forgets to write an overriding method. It won't be caught at compile-time, but at least it might be caught during testing.
I'm not sure how legitimate this reason is, since it's also possible to define a new abstract class NewImprovedWhatever that extends the old one, to contain the new methods. That may pose its own maintenance challenges, though. I'm not sure.
I did notice that Java defines an abstract class java.net.SocketImpl, that contains two non-abstract methods, shutdownInput() and shutdownOutput(), whose default implementation is to throw an exception:
protected void shutdownInput() throws IOException {
throw new IOException("Method not implemented!");
}
The comments indicate that they were added in 1.3, so perhaps that's the exact reason it was done this way, i.e. not to require modification of other classes that already extended SocketImpl. But I don't know for sure.
In any case, a design like this would surely be really bad code, if the class were designed that way from scratch. But the nice O-O concepts we learn about in class aren't always so nice in practice when existing code has to be modified.
I have sometimes thrown UnsupportedOperationException from a method whose functionality has not yet been implemented. (There is also a NotImplementedException in Apache Commons which is a subclass of UnsupportedOperationException.) This was always meant as a placeholder and a message to others using the related class or service that the method is not yet complete. Such code never made it to production, however.
The purpose of doing this would be to purposefully write BAD CODE.
If one wants to confuse its readers and want them to feel the agony of going through their code, then one writes such code.
It also shows lack of designing skills in the code.
A poorly written API will have such code.
Don't do that.

Protected "stub" methods used only for overriding purposes considered good practice or not?

Sometimes when I extend one of my own classes, I want to (for the purpose of the subclass) "inject" one or two lines of code in the middle a method in the super class.
In these cases I sometimes add a call to an empty protected method for the subclass to override.
public void superClassMethod() {
// some fairly long snippet of code
doSubclassSpecificStuff();
// some other fairly long snippet of code
}
// dummy method used for overriding purposes only!
protected void doSubclassSpecificStuff() {
}
When doing this several times in the same class I must say it looks quit awkward / ugly so my questions:
Is this way of "opening up" for subclasses to "inject" code in the middle of methods considered good practice or not?
Is the pattern (anti-pattern?) called something?
Has it been used in any well known API / library? (Note that I'm talking about non-abstract classes.)
Are there any better alternatives?
The only alternative I can come up with is to use something like the command pattern and have a setMiddleOfMethodHandler(SomeRunnableHandler), and call handler.doSubclassSpecificStuff() instead of the dummy-method. It has a few drawbacks as I see it though, such as for instance not being able to touch protected data.
You've just discovered the Template method design pattern. Note though that normally the methods that comprise the individual steps are abstract (rather than empty and protected) so that subclasses must override them.
There is the Template method pattern. The idea there is that much of the work is common, except for a few bits, which are handled by a subclass implemented method.
Yes, this is a legitimate way to do things; I've used it myself.
The only problem I can see is not the specific technique, but the fact that you are using subclasses of concrete (read: non-abstract) classes at all. Subclassing concrete classes has many subtle problems, so I would recommend to avoid it altogether. See e.g. http://en.wikipedia.org/wiki/Liskov_substitution_principle for an explanation of what you must do to properly subclass a class, and the problems involved. Also, in "Effective Java" Block recommends using composition (Item 16).
Another approach (that avoids subclassing) would be to use Dependency Injection. Your method would accept a parameter of a type that implements the interface ISpecificStuff, which specifies a method doSubclassSpecificStuff():
public void superClassMethod(ISpecificStuff specificStuff) {
....
specificStuff.doSubclassSpecificStuff();
....
}
That way, any caller can decide what the method should do. This avoids the need for subclassing. Of course, you could inject via a constructor, if you need it in more than one method.
It looks fishy to me. I think the reason you're ending up having to do this is a design flaw. Your method that needs to be "split" probably does too much. The solution would be to break it up in steps, and give that "doSubclassSpecificStuff" step a specific meaning.
For ex.:
void Live()
{
BeBorn();
DoCrazyStuff(); // this can be made protected virtual
Die();
}
Yes, it's perfectly fine. This is an example of the Template Method pattern, where you use inheritance to define a method that maintains a known "skeleton", but can have custom logic.
public abstract class Ancestor
{
protected virtual void CanOverrideThisStep(){...}
protected abstract void MustDefineThisStep();
protected sealed void MustDoExactlyThis(){...}
private void HideThisStepFromEveryone(){...}
public sealed void TemplateMethod()
{
...
CanOverrideThisStep();
...
MustDoExactlyThis();
...
MustDefineThisStep();
...
HideThisStepFromEveryone();
}
}
Inheritors of Ancestor above must define a body for MustDefineThisStep(), and may at their option override CanOverrideThisStep(), but cannot touch MustDoExactlyThis(), HideThisStepFromEveryone, or the TemplateMethod driving function itself. However, except for HideThisStepFromEveryone, all the submethods are available to child classes, so a child may use MustDoExactlyThis() in the implementation of MustDefineThisStep().
This is very common; such constructions are the reason OO languages have such access modifiers such as these at their disposal. The pattern is very useful for workflows, file processing, and other tasks that are generally the same but have slightly different implementation details.
I routinely use this technique as a way to handle special cases. I'll write things like this:
public void foo()
{
theData=getTheData();
preprocessDataHook(theData);
putTheData(theData);
}
protected void preprocessDataHook(SomeObject theData)
{
// Nop. Available for subclasses to override.
}
A subclass that does not need to preprocess the data can then just not override this function. A subclass that does need to preprocess can override the function.
If we expected that all or most subclasses would need to preprocess, then this should be an abstract function to force the programmer to implement it, or make a conscious decision to do nothing. But if it's just an occassional subclass that needs to do something here, I think this is a perfectly valid approach.

#Override on Implementation

Would you put the annotation in implementation class methods? Does it serve any purpose? If you mistype or don't have it, it is a compile error anyway.
While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override fails to correctly override a method in one of its superclasses, the compiler generates an error. Its better to fail fast, catch the error soon rather than later figure out you wrote hashcode() but you meant to write hashCode(). #Override helps in finding the problem sooner rather than later.
Similar questions on SO.
when-do-you-use-javas-override-annotation-and-why?
should-i-add-an-override-annotation-when-implementing-abstract-methods?
Also see this.
It's rather useful. If a method annotated with #Override doesn't really overrides method in a superclass you'll get a compilation error.
For example, if you have a class Foo and you create a method:
#Override
public boolean equals (Foo foo) { ... }
then you'll get compile-time error which will tell you that equals (Foo foo) doesn't override any method in Foo's superclass.
Modern IDEs (like IntelliJ) add this annotation automatically when you use some code-generation features of the IDE.
I assume you are asking about annotating methods which are defined in an implemented interface, or as abstract in a super class. In that case, you are correct that a typo in the method signature will result in a compile error with or without #Override. However, I think the annotation is still helpful to explicitly mark a method as implementing an interface. If the interface ever changes, having #Override annotations on all the implementing methods can help pinpoint which method signatures have changed and need to be updated.
More importantly, as mklhmnn mentioned in his answer, if a method is removed from the interface, the #Override annotation in your implementing class will cause a compile error. Without the annotation, you might not be aware that a method had been removed from the interface, which could lead to subtle bugs.
I don't use it and never had a problem. I don't know why suddenly everybody starts using it (Eclipse? which I don't use either).
Refactoring is not a problem, IDE checks that for you anyway.
#Override may help code readability though, so that it's clear to HUMANS what's going on, not compilers. Although my IDE will also mark override methods graphically, it is not very prominent, but the point remains, this is something tools can do for us automatically.
Marking a method as #Override will produce a compilation error if the API changes so no super method is available any more. Maybe that's the reason.
I think it's also nice to do this as an indication to yourself that the Javadoc is elsewhere, you didn't just forget it.

Should I add an #Override annotation when implementing abstract methods in Java?

When overriding a non-virtual method in Java, use of the #Override annotation is recommended, but what if I implement an abstract method? Should I use #Override then as well?
I tend to prefer the use of #Override in this case, so that the method gets flagged in the subclasses if the superclass changes (either removing the method altogether, or changing its signature, etc.).
The only real difference is that without the annotation, if the method in the superclass/interface is changed or removed, the implementation in question simply becomes a "normal" method of that class. Thus you should add the annotation if you're implementing the method solely to fulfil the contract; and you probably shouldn't add it if the method makes sense in your class regardless of any implemented interfaces or inherited abstract methods.
Yes - again, it tells the compiler, "I really want to be overriding a method here. If there isn't a corresponding method to override, I've made a mistake and want to be told about it!"
Personally I think it's a pity that this is just an annotation rather than part of the language (as it is in C#) but that's the benefit of hindsight, of course.
Yes. It is recommended practise by Joshua Bloch in Effective Java.
Actually, Joshua Bloch, in the final paragraph of page 178 in Effective Java (2nd Ed.), says that it's not essential for methods of concrete classes that override abstract methods to use the Override annotation because the compiler would give an error anyway. However, "it is not harmful to do so".
I'd recommend choosing a strategy and sticking with it consistently.

Categories

Resources