Question:
Consider the following Java code snippet:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.sound();
animal2.sound();
}
}
Explain the concept of inheritance and polymorphism in the context of the given code snippet. Describe the output that would be produced when the code is executed. Provide a step-by-step explanation.
Answer:
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) where a class can inherit the properties and behaviors (methods) of another class. The class that inherits is called the child or subclass, and the class being inherited from is called the parent or superclass.
Polymorphism is a concept that allows objects of different classes to be treated as objects of a common superclass. This means that a variable of the superclass type can refer to objects of its subclasses. When a method is called on a variable of the superclass type, the method defined in the subclass will be executed if it overrides the superclass method.
In the given code snippet, we have three classes: Animal
, Cat
, and Dog
. The Cat
and Dog
classes inherit from the Animal
class.
In the main
method, two objects are created: animal1
of type Animal
referring to a Cat
object, and animal2
of type Animal
referring to a Dog
object.
When the sound
method is called on animal1
, since animal1
is referring to a Cat
object, the sound
method in the Cat
class overrides the sound
method in the Animal
class. Therefore, the output would be:
Meow
Similarly, when the sound
method is called on animal2
, since animal2
is referring to a Dog
object, the sound
method in the Dog
class overrides the sound
method in the Animal
class. Therefore, the output would be:
Woof
In summary, the output of the given code snippet would be:
Meow
Woof
This demonstrates the concept of polymorphism, where objects of different classes (Cat
and Dog
) are treated as objects of a common superclass (Animal
) and the appropriate method implementation is executed based on the actual object type being referred to.