What is @Override annotation in java?
Before going to learn @Override annotation learn the concept of Method Overriding.@Override: Annotation will verify whether a method is available in sub class is exists in a super class or not. If the method is available is subclass and superclass then the compiler will not throw any error.
See below example:
class parent {
public void display(){
System.out.println("parent Class Method");
}
}
class child extends parent{
@Override
public void display(){
System.out.println("child class method");
}
}
class overrideDemo{
public static void main(String[] args){
parent p=new child();
p.display(); //output: child class method
}
}
Here, we are creating a reference variable to parent class and object for the child class. And we assigned @Override annotation to display() method in a subclass.
When we compile the @Override method will verify display() is available in the subclass as well as in superclass. A method is an available compiler will not throw any error.
When we compile the @Override method will verify display() is available in the subclass as well as in superclass. A method is an available compiler will not throw any error.
Let see another case:
class parent {
public void display(){
System.out.println("parent Class Method");
}
}
class child extends parent{
@Override
public void Display(){
System.out.println("child class method");
}
}
class overrideDemo{
public static void main(String[] args){
parent p=new child();
p.display(); //throws error
}
}
Here,observe by mistake a programmer written a method as Display() in subclass and display() in superclass.There is a mismatch in method name.Then compiler will throw error like below:
@Override Annotation |
So @override annotation is useful to verify several methods available in sub class as well as in super class.
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.