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:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free. Share your stuff here so that others can get benefitted.