Junior — Middle
What are the differences between inheritance and polymorphism concepts in object-oriented programming?
sobes.tech AI
Answer from AI
Inheritance and polymorphism are two key principles of object-oriented programming, but they solve different problems:
-
Inheritance allows creating a new class based on an existing one, inheriting its properties and methods. This promotes code reuse and the creation of class hierarchies.
-
Polymorphism allows objects of different classes related by inheritance to use the same interface or method, but with different implementations. This provides flexibility and extensibility of code.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Outputs "Bark" — an example of polymorphism
}
}
Here, inheritance is creating classes Dog and Cat based on Animal, and polymorphism is calling the sound() method on an Animal reference that actually points to a Dog object, which executes the Dog's implementation.