Polymorphism : Method Overriding

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

Polymorphism : 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