In this tutorial, we will learn about method overriding in Java with the help of examples.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
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.
// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("From parent m1()");
}
protected void m2()
{
System.out.println("From parent m2()");
}
}
class Child extends Parent {
// new m1() method
// unique to Child class
private void m1()
{
System.out.println("From child m1()");
}
// overriding method
// with more accessibility
@Override
public void m2()
{
System.out.println("From child m2()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
Output:
From parent m2()
From child m2()