Java-Method Overriding

Method Overriding

When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.

For example, in the following program, when print( ) is invoked on an object of type Sub, the version of print( ) defined within Sub is used. That is, the version of print( ) inside Sub overrides the version declared in Super.

Program

final


Program Source

class Super {
    
    void print()
    {
        System.out.println("SuperPrint");
    }
}

class Sub extends Super{
    
    void print()
    {
        System.out.println("SubPrint");
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Sub obj = new Sub();
        obj.print();
    }
}

Leave a Comment