What is inheritance and polymorphism in the context of reference data types?
sobes.tech AI
Answer from AI
Inheritance is a mechanism that allows creating a new class (derived, child) that inherits fields and methods from an existing class (base, parent). This promotes code reuse and the creation of class hierarchies.
Polymorphism is the ability of objects of different classes to behave uniformly or differently when calling the same method. There are two main types: static (method overloading) and dynamic (method overriding).
In the context of reference data types, inheritance allows creating a variable of the base class that can refer to an object of the derived class. Polymorphism in this case manifests in that when calling a method through such a variable, the version of the method from the actual type of the object is executed, not from the reference type (dynamic polymorphism).
Example in Java:
// Base class
class Animal {
public void makeSound() {
System.out.println("Makes a sound");
}
}
// Derived class 1
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
// Derived class 2
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Variable of type Animal refers to a Dog object
Animal myCat = new Cat(); // Variable of type Animal refers to a Cat object
myDog.makeSound(); // Calls the method from Dog (polymorphism)
myCat.makeSound(); // Calls the method from Cat (polymorphism)
}
}
In this example, myDog and myCat have the reference type Animal, but thanks to polymorphism, calling makeSound() executes the corresponding implementation from Dog and Cat.