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

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.

Related

How to invalidate a super-interface method

First I want to clarify that I don't have any real business requirements for that, It's a purely theoretical question.
Assuming that we have these two Interfaces :
public interface SuperInterface {
void doSuperStaff();
void doComStaff();
}
public interface SubInterface extends SuperInterface {
// Something here to invalidate doSuperStaff()
}
Is there any way to invalidate / disable the doSuperStaff() for all classes that implement the SubInterface? So only the classes that directly implement SuperInterface can use that method and override it.
NB: I know that we can resolve that in a conceptual manner, but I want to know if there is a way to make that possible technically: using annotations for example ( like the #Deprectaed, which only instructs the compiler that the method is deprecated.)....
Limited, but the following helps a bit.
public interface SubInterface extends SuperInterface {
#Deprecated
void doSuperStaff();
}
Or even
public interface SubInterface extends SuperInterface {
#Deprecated
default void doSuperStaff() {
throw new UnsupportedOperationException("...");
}
}
UPDATE If it's purely theoritical and you are not stuck with a legacy design you can't change, then it's bad idea to try and remove Super interface methods on a sub-interface (or class). It's indicative the design is wrong (Dog -> Animal (useLegs, hasBody), Owl -> Animal (useLegs-??, hasBody). useLegs in this case doesn't belong in Animal.
But if you have legacy code you want to remove it from, and enforce it with Compile-time errors, this approach will work.
You can remove the method with Aspects. Create a pointcut that triggers when the method is called, add Around Advice which is triggered on that pointcut and throws an unsupported operation exception rather than proceed.
With AspectJ Spring syntax it looks something like this (Syntax details here -http://www.eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html)
#Around("call(* SubInterface.doSuperStuff())")
public Object removeMethod(ProceedingJoinPoint thisJoinPoint) {
throw new UnsupportedOperationException("...");
}
You can also use the native AspectJ language and it's Eclipse plugin to have Eclipse (or your build) show a compile error on the call site if any code attempts to use it. I think that would look something like this (https://eclipse.org/aspectj/doc/released/adk15notebook/annotations-decp.html)
declare error : call(* SubInterface.doSuperStuff())
: "Method doSuperStuff removed from SubInterface";
As you said the answer is NO.
This is simple illustration, why this feature cannot be added.
Firstly the meaning of Interface in Java is Behavior
Suppose if I create a new interface AdavancedComparable<T> which extends java.lang.Comparable<T> and if I deprecate the public int compareTo(T o); in my AdvancedComparable interface and add my own method like advancedCompare(T o);
public interface AdavancedComparable<T> extends Comparable<T> {
// invalidate/deprecate for compareTo method using requested feature somehow
public int advancedCompare(T o);
}
Any method which is accepting Comparable<T> type parameter will also accept AdvancedComparable<T> type parameter, but when the method tries to call compareTo, it will break if the feature you asked is implemented.
Suppose if compiler updated to recognize this issues and made to throw compile time error, that's fine, but it also has to support the legacy code. Remember the Generics case, many classes which altered to support generic type, supports Raw type too (Like List, Class etc). Just to support legacy code. But in our case it is difficult to do so, I feel.
Can not you use super Abstract Class which would implement doSuperStuff() and other concrete class could extend it to override other method.
You can always cast a subtype to a supertype, and invoke methods in the supertype.
However, there is a way to prevent overriding --
public interface SuperInterface
Object doSuperStaff(); // return value doesn't matter, can be null
public interface SubInterface extends SuperInterface
default Foo doSuperStaff() { ... }
Here, Foo is a package-private type. Subclasses of SubInterface (in different packages) have no way to override this method, because they can't access Foo.
It's also possible to use a private class Foo there.

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.

#Override annotation in Java

When I implement an Interface in Java, for instance:
public interface IColumnHeader {
public String getHeaderValue();
public String findColumnValueFromHeaderValue(String parseFrom);
}
the following enum implements the above interface:
public enum FileColumnDwellTime implements IColumnHeader {
REPORTER_USER_ID {
#Override
public String getHeaderValue() {
return "reporter_user_id";
}
#Override
public String findColumnValueFromHeaderValue(String parseFrom) {
return parseFrom;
}
};
}
Why does implementing an interface in Java and implementing the methods from the interface introduce the #Override annotation. Isn't that a total misnomer?
Shouldn't that annotation actually be called something like "#Implementation"?
The #Override annotation would be more apt for subclasses that actually override superclass methods that are predefined. In the case of simply implementing a method from an interface, there is no actual overriding being done.
Am I right?
(If I were the JLS writers for Java 9, I would have a new annotation called #Implementation that would "subclass" the #Override annotation, in the case of implementing methods from interfaces, and the like.)
Taking a look at the JLS, it just seems to be how it's defined. I'm looking at JLS 8, not sure if the section I'm going to quote was different in earlier versions (although I highly doubt it will, since interface interactions shouldn't have changed). From section 8.4.8.1:
An instance method mC declared in or inherited by class C, overrides from C another
method mI declared in an interface I, iff all of the following are true:
I is a superinterface of C.
mI is an abstract or default method.
The signature of mC is a subsignature (§8.4.2) of the signature of mI.
So at least based on this, the #Override annotation makes sense, since it denotes an instance method that overrides a method declared in an interface, based on the definitions in the JLS.
Unfortunately, I can't give an authoritative answer as to why this is called overriding, but here's sort of how it works in my head:
If you inherit an abstract method (like one in an interface), your class implicitly contains the signature for that method in its body. When you implement the method corresponding to that signature, you replace (and thus override) the inherited abstract method signature with one corresponding to a concrete implementation. So it makes sense to have #Override, right?
In addition, this way #Override would work for overridden methods regardless of whether they were technically an implementation or "truly" overridden. And why make more work for yourself (and compiler designers) than you have to?
I know that that's a rather bad view of how inheritance works, but I hope it makes sense.
So I guess in the end, I would say you are wrong. There is overriding being done. But I wouldn't say it's immediately obvious why that is the case. Interesting question!

JVM - Order of execution of sub class methods and the use of #override [duplicate]

This question already has answers here:
When do you use Java's #Override annotation and why?
(27 answers)
Closed 9 years ago.
This is a newbie question.
I read that JVM's execution starts from searching for the methodname from lowest class in the hierarchy and if the method is not available in that class it traverses to the parent class looking for the method.
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class ?
The below example illustrates my question
class superclassA
{
method()
{
}
}
class subclassB extends superclassA
{
#Override
//While executing if JVM starts looking for the method name from the lowest hierarchy
//then why do we have to use "override" as the methodname will be matched from the lowest level itself?
method()
{
--custom subclass specific code...
}
}
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class?
We don't. The #Override annotation has no technical meaning - it exists to document the fact that this method overrides one in the superclass, which has some advantages:
If you look at the code, it tells you there is an superclass method that might be important to understand what this method does
You will get a compiler error if the superclass method's signature changes in a way that the subclass method does in fact not override it anymore.
You can get a compiler warning if you override a method without using the annotation, in case you do it inadvertantly.
#Override simply helps Java compiler detect errors in source code, compilers are generate an error if a method annotated with #Override does not override it in fact.
It is not mandatory to annotate a method that overrides a supertype methods with #Override.
You don't need #Override. But it's a useful annotation that causes the compiler to check whether or not you are really overriding the method that you say you are. When you #Override a method that is not actually overriding a method, the compiler will inform you of this discrepancy. Additionally, it just makes your code more clear: since all methods in Java are implicitly virtual, and a method in a derived class with the same signature as that of a non-final method in a super class implicitly overrides it1, adding #Override makes the code easier for humans to understand.
1: To be clear, you can not have a method in a derived class with the same signature as a final method in a super class.

What's "#Override" there for in java?

public class Animal {
public void eat() { System.out.println("I eat like a generic Animal."); }
}
public class Wolf extends Animal {
#Override
public void eat() { System.out.println("I eat like a wolf!"); }
}
Does #Override actually have some functionality or it's just kinda comment?
From the Java Tutorials on annotations:
#Override — the #Override annotation
informs the compiler that the element
is meant to override an element
declared in a superclass (overriding
methods will be discussed in the the
lesson titled "Interfaces and
Inheritance").
// mark method as a superclass method
// that has been overridden
#Override
int overriddenMethod() { }
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.
Let's take a look at the example given in the Java Language specifications, 9.6.1.4 Override. Let's say you want to override a method, equals in that case, but you wrote:
public boolean equals(Foo that) { ... }
instead of:
public boolean equals(Object that) { ... }
While this code is legal, annotating the equals method declaration with #Override would trigger a compile time error because you're in fact not overriding it, you're overloading it. This can cause nasty bugs and the Override annotation type helps at detecting them early.
Override annotation is a compile time annotation which makes java compiler throw an error if the method having this annotation is actually not overriding a parent class method.
You can try to change the Wolf class to not extend the Animal class and if Override annotation is present it will show you a compile time error
something like it alerts at compile time by throwing compilation error if you are not really overriding the method.
similar Q here-When do you use Java's #Override annotation and why?
It works as a comment, but also as an assertion that you actually ARE overriding something. If you use #Override, but it does not actually override anything, the compiler will generate an error. See the documentation page for more details.
If you remove the "eat" method from the parent class or misspell it as "eats" in the subclass, your code will now fail to compile. Without the "#Override" annotation, you can do either and your code will still compile, it just won't do what you want (namely, override a method).
It does not do anything at run-time, but it helps you to catch errors:
If you thought you would override a method, but do not (because of a speling problem or parameter types), without the annotation, the code would compile to something useless (as in: your method would not be called, but the superclass method that you accidentally did not override gets called).

Categories

Resources