Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("In parent m1()");
}
protected void m2()
{
System.out.println("In parent m2()");
}
}
class Child extends Parent {
// new m1() method
private void m1()
{
System.out.println("In child m1()");
}
// overriding the protected method
@Override
public void m2()
{
System.out.println("In child m2()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2(); // call the object's method of child
}
}
output:
In parent m2() In child m2()