Question: Explain the concepts of inheritance and polymorphism in object-oriented programming. Provide an example in Java to demonstrate inheritance and polymorphism, and explain how the program exhibits these two concepts in action.
Answer: Inheritance and polymorphism are two fundamental concepts in object-oriented programming. Inheritance allows a class to inherit properties and behaviors from another class, while polymorphism allows objects to be treated as instances of their parent class.
Inheritance enables a new class to take on the properties and methods of an existing class. This promotes code reusability and allows for the creation of a hierarchy of classes with shared characteristics.
Polymorphism allows objects of different classes to be treated as objects of a common parent class. This allows for flexibility in the design and implementation of object-oriented systems.
Example in Java:
// Parent class
class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof woof!
}
}
Explanation:
In the given example, the Animal
class serves as the parent class, and the Dog
class inherits from the Animal
class. The makeSound
method is overridden in the Dog
class, demonstrating inheritance.
The Main
class demonstrates polymorphism by creating an instance of the Dog
class and assigning it to a variable of type Animal
. Despite the variable being of type Animal
, it is able to call the makeSound
method of the Dog
class, illustrating polymorphic behavior.
This code illustrates inheritance and polymorphism in action, as the Dog
class inherits the makeSound
method from the Animal
class and exhibits polymorphic behavior when assigned to a variable of type Animal
.