Home Java Jdk7 Polymorphism : Method Overriding
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Polymorphism : Method Overriding

Advertisement
In this tutorial you will learn another concept of polymorphism that is method overriding.

Polymorphism : Method Overriding

In this tutorial you will learn another concept of polymorphism that is method overriding.

Method Overriding  :

Method overriding is also called Function overloading. It is one of the implementation of polymorphism, which allows a subclass to override the method of the super class. In method overriding ,we rewrite superclass method into subclass.

Example :

In this example, A is our super class and B is our subclass. We are overriding show() method of A  into class B. In show() method of Class A ,we are printing sum of two int type variables x and y, In class B again rewriting the show() method which has same return type and same parameter as show() method of class A. That is we are overriding show() method.

class A {
int x = 10, y = 20;

public int sum() {
return x + y;
}

public void show() {
System.out.println("Super class method show()");
System.out.println("Sum of two numbers : " + sum());
}
}

class B extends A {
public int sum(int x, int y, int z) {
return (x + y + z);
}

public void show() {
System.out.println("Overriding superclass method show()");
System.out.println("Sum of three numbers : " + sum(10, 20, 30));
}
}

public class MethodOverriding {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.show();
b.show();
}
}

Output:

Super class show() method
Sum of two numbers : 30
Overriding super class method show()
Sum of three numbers : 93
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



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: December 17, 2012

Related Tutorials

Ask Questions?    Discuss: Polymorphism : Method Overriding  

Post your Comment


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