Image

Java - Core Java - Method overriding

Method overriding

Method overriding is the process of writing functionality for methods with same signature and return type, both in super class and subclass. if sub class has same method as declared in the parent class it is known as method overloading. in other word if subclass is provide the specific implementation of the method that has been provide by one of its parent class .

If subclass has the same method as declared in the parent class that is called as method overriding.

Rules method overriding

1. method must have same name as in the parent class.
2. method must have same parameter as in the parent class.
3. method IS-A relationship.
WAP to understand method overriding
class A
{
    A(){
        System.out.println("I am in Constructor ");   
    }
    public void showA()
    {
        System.out.println("I am in A ");   
    }
}
class B extends A{
    public void showA(){
        System.out.println("I am in B ");   
    }
}

class UsemeJava {

    public static void main(String[] args) {
        B b=new B();
        b.showA();
    }
    
}
O/P
D:\classes>javac UsemeJava.java

D:\classes>java UsemeJava
I am in Constructor
I am in B