Polymorphism in Java

0
216

This tutorial is all about Polymorphism in Java.
Polymorphism
is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

In polymorphism, two things internally process:

  1. Method Overriding
  2. Auto upcasting

Together both brings polymorphism. Inheritance is used for polymorphism.

Let’s take one example

[java]

class A{

void test(){

System.out.println(“A-test”);

}

}

class B extends A{

void test(){  //method overriding

System.out.println(“B-test”);

}

}

class Manager(){

public static void main(String[] ar) {

A a1=new A();

A a2=new B(); //upcasting

a1.test();

a2.test();

}

}

Output:

A-test

B-Test

[/java]

 

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.