Java OOP - 4 - MethodOverriding PDF
Java OOP - 4 - MethodOverriding PDF
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
We can only use those access specifiers in subclasses that provide larger access than the access specifier of the superclass.
For example,
Suppose, a method myClass() in the superclass is declared protected. Then, the same method myClass() in the subclass can
be either public or protected, but not private
class Animal {
protected void displayInfo() {
System.out.println("I am an animal.");
}
} In the above example, the subclass Dog overrides the method
displayInfo() of the superclass Animal.
class Dog extends Animal {
public void displayInfo() { Whenever we call displayInfo() using the d1 (object of the subclass),
System.out.println("I am a dog."); 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
class Main { Dog subclass. This is possible because the public provides larger
public static void main(String[] args) { access than the protected.
Dog d1 = new Dog();
d1.displayInfo();
}
}
Important Questions on Method Overriding
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphis.