You are here: Home / Topics / Program to explain Polymorphism in Java

Program to explain Polymorphism in Java

Filed under: Java on 2023-09-17 07:01:53

//  Program to explain Polymorphism or 
//  Dynamic Method Dispatch or Run Time Binding.

class  Shape
{
void draw()
{
 System.out.println("Drawing Shape.");
}
}

class  Rectangle extends Shape
{
void draw()
{
 System.out.println("Drawing Rectangle.");
}
}

class  Triangle extends Shape
{
void draw()
{
 System.out.println("Drawing Triangle.");
}
}

class  PolymorphismTest6
{
public static void main( String args[ ] )
{
 Shape s = new Shape();
 s.draw();
 
 Rectangle r = new Rectangle();
 s = r;
 s.draw();
 
 Triangle t = new Triangle();
 s = t;
 s.draw();
}
}

 

Output:  

Drawing Shape.
Drawing Rectangle.
Drawing Triangle.

About Author:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.