Home Java Javatutorial Method Overriding in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Method Overriding in Java

Advertisement
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 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

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 1, 2013

Ask Questions?    Discuss: Method Overriding in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com