Abstract Class Polymorphism

This program demonstrates polymorphism using abstract classes.

Problem Statement

Write a Java program where abstract class Shape is extended by Circle and Rectangle.

Source Code

1 abstract class Shape { abstract void draw(); }
2 class Circle extends Shape { void draw(){ System.out.println("Eduinq Drawing Circle"); } }
3 class Rectangle extends Shape { void draw(){ System.out.println("Eduinq Drawing Rectangle"); } }
4 public class AbstractClassPolymorphism {
5 public static void main(String[] args) {
6 System.out.println("Eduinq Abstract Class Polymorphism");
7 Shape s1=new Circle();
8 Shape s2=new Rectangle();
9 s1.draw(); s2.draw();
10 }
11 }

Program Output

					Eduinq Abstract Class Polymorphism
Eduinq Drawing Circle
Eduinq Drawing Rectangle
				

Explanation

Abstract classes define method signatures without implementation, enforcing a contract for subclasses. - Circle and Rectangle provide their own implementations of draw(). - Polymorphism allows the abstract reference Shape to point to different subclass objects, executing the correct method at runtime. - This design ensures consistency while allowing flexibility, which is vital in large systems where multiple types must adhere to a common interface but behave differently. Conclusion: Shows abstract class polymorphism.

Quick Links to Explore