Java Method Overriding
Java Method Overriding
In this tutorial, we will learn about method overriding in Java with the help of
examples.
Now, if the same method is defined in both the superclass and the subclass,
then the method of the subclass class overrides the method of the superclass.
This is known as method overriding.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am a dog.
Notice the use of the @Override annotation in our example. In Java, annotations
are the metadata that we used to provide information to the compiler. Here,
the @Override annotation specifies the compiler that the method after this
annotation overrides the method of the superclass.
It is not mandatory to use @Override . However, when we use this, the method
should follow all the rules of overriding. Otherwise, the compiler will generate
an error.
Java Overriding Rules
Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am an animal.
I am a dog.
In the above example, the subclass Dog overrides the method displayInfo() of
the superclass Animal .
When we call the method displayInfo() using the d1 object of the Dog subclass,
the method inside the Dog subclass is called; the method inside the superclass
is not called.
Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to
call displayInfo() of the superclass.
It is important to note that constructors in Java are not inherited. Hence, there
is no such thing as constructor overriding in Java.
However, we can call the constructor of the superclass from its subclasses.
For that, we use super() . To learn more, visit Java super keyword.
Access Specifiers in Method Overriding
The same method declared in the superclass and its subclasses can have
different access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide larger
access than the access specifier of the superclass. For example,
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am a dog.
In the above example, the subclass Dog overrides the method displayInfo() of
the superclass Animal .
Whenever we call displayInfo() using the d1 (object of the subclass), the
method inside the subclass is called.
Notice that, the displayInfo() is declared protected in the Animal superclass. The
same method has the public access specifier in the Dog subclass. This is
possible because the public provides larger access than the protected .
We will learn more about abstract classes and overriding of abstract methods
in later tutorials.
REFERENCES: https://www.programiz.com/java-programming/method-overriding