Polymorphism
Polymorphism:
Explanation :
Example:
Definition:
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
Explanation :
Polymorphism enables code to work with objects of various classes through a common interface. Method overloading and overriding facilitate polymorphism.
Example:
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a square.");
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[] { new Circle(), new Square() };
for (Shape shape : shapes) {
shape.draw(); // Output:
Drawing a circle. Drawing a square.
}
}
}
Comments
Post a Comment