Java Method overriding

If a subclass provides a method with the same signature (name and parameter) as in its superclass, then the subclass overrides the method of its superclass. This process of overriding a superclass method by a subclass is known as method overriding.

Conditions for method overriding:

  1. The method in a subclass must have the same signature as in its superclass.
  2. Two classes must follow the IS-A relationship.

Developer.java

package com.w3schools;

public class Developer {
    public void show(){ 
        System.out.println("Developer details."); 
    }
}

JavaDeveloper.java

package com.w3schools;

public class JavaDeveloper extends Developer{

    public void show(){
          System.out.println("Java Developer details.");
    }

    //main method
    public static void main(String args[]){
    	JavaDeveloper obj = new JavaDeveloper();
       
    	//subclass overrides superclass method
        //hence method of JavaDeveloper class method will be called.
        obj.show();
    }
}

Output:

Java Developer details.

Can the static method be overridden?

No, Static methods can’t be overridden because they are associated with the class, not with the object.

Role of access modifiers in method overriding:

The access modifier of the overridden method in the subclass can’t be more restrictive than in super superclass. Otherwise, it will throw an exception.

package com.w3schools;

public class JavaDeveloper extends Developer{

    protected void show(){
          System.out.println("Java Developer details.");
    }

    //main method
    public static void main(String args[]){
    	JavaDeveloper obj = new JavaDeveloper();
       
    	//subclass overrides superclass method
        //hence method of JavaDeveloper class method will be called.
        obj.show();
    }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Cannot reduce the visibility of the inherited method from Developer

    at com.w3schools.JavaDeveloper.show(JavaDeveloper.java:5)
    at com.w3schools.JavaDeveloper.main(JavaDeveloper.java:15)

 

Please follow and like us:
Content Protection by DMCA.com