Polymorphism
In object-oriented design, polymorphism refers to the ability of objects of different classes to be treated as the same type. This allows for flexibility and extensibility in your code.
Let's consider an example with animals. Suppose we have a base Animal
class and two subclasses, Dog
and Cat
. Each class has its own makeSound()
method.
1class Animal {
2 public void makeSound() {
3 System.out.println("The animal makes a sound");
4 }
5}
6
7class Dog extends Animal {
8 public void makeSound() {
9 System.out.println("The dog barks");
10 }
11}
12
13class Cat extends Animal {
14 public void makeSound() {
15 System.out.println("The cat meows");
16 }
17}
18
19public class Main {
20 public static void main(String[] args) {
21 Animal animal1 = new Dog();
22 Animal animal2 = new Cat();
23
24 animal1.makeSound();
25 animal2.makeSound();
26 }
27}
In this example, we create objects of type Dog
and Cat
and assign them to variables of type Animal
. We can then call the makeSound()
method on these variables.
The output of the above code will be:
1The dog barks
2The cat meows
Even though the variables animal1
and animal2
are of type Animal
, the actual objects they refer to are Dog
and Cat
, respectively. The makeSound()
method is invoked based on the actual type of the object.
Polymorphism is particularly useful when working with collections of objects. For example, you can have an array or a list of Animal
objects that can contain instances of different subclasses.
By treating all the objects as Animal
, you can perform common operations on them without worrying about their specific types.
In summary, polymorphism in object-oriented design allows objects of different classes to be treated as the same type, providing flexibility and extensibility in your code.
xxxxxxxxxx
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}