Method Overriding in Java

Method Overriding in Java means a Subclass uses extends keyword to override a super class method. In Overriding both subclass and superclass must have same parameters. Method Overriding is used so that a subclass can implement a parent class method and then modify the parent class as needed.

Method Overriding in Java

Method Overriding in Java means a Subclass uses extends keyword to override a super class method. In Overriding both subclass and superclass must have same parameters. Method Overriding is used so that a subclass can implement a parent class method and then modify the parent class as needed.

Method Overriding in Java


Method Overriding in Java means a Subclass uses extends keyword to override a super class method. In Overriding both subclass and superclass must have same parameters.

Method Overriding in Java is used so that a subclass can implement a parent class method and then modify the parent class as needed.

While using Method Overriding, following points should be kept in mind:

  • Overridden method must be similar to argument list.
  • Return types and constructor parameters of methods must match.
  • The access level of sub class cannot be more restrictive than that of super class.
  • Final method cannot be overridden.
  • Static method cannot be overridden but can be re-declared.
  • Instance methods can be overridden only if they are inherited by the subclass.

Example of Method Overriding in Java :

package Overriding;

class A {
	public void call() {  
		System.out.println("Print of A ");
	}
}

class AB extends A {
	public void call(String string) {
		System.out.println("Print of AB ");

	}
}

class AC extends A {
	public void call(String string) {
		System.out.println("Print of AC ");
	}
}

public class Example2 {
	public static void main(String[] args) {
       
		A a = new A();
		 AB ab = new AB();
		 AC ac = new AC();
		 //a.call();
		   ab.call("");
		   ac.call("");
	}

}

Output:

Print of AB

Print of AC