Sobes.tech
Junior

What is the difference between inheritance and polymorphism?

sobes.tech AI

Answer from AI

Inheritance is a mechanism that allows a class (subclass, child class) to inherit fields and methods from another class (parent, superclass). This promotes code reuse.

Polymorphism is the ability to use the same interface to represent different underlying forms. In the context of Java, it means that a reference variable can refer to an object of its own type or any of its subtypes. There are compile-time polymorphism (method overloading) and runtime polymorphism (method overriding).

Main differences:

  • Inheritance defines relationships between classes (parent-child) and allows code reuse.
  • Polymorphism allows accessing different objects through a common interface, executing the appropriate method depending on the actual type of the object at runtime.

Example of runtime polymorphism:

class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog(); // Polymorphism: an Animal reference points to a Dog object
        Animal myCat = new Cat(); // Polymorphism: an Animal reference points to a Cat object

        myDog.sound(); // Calls the sound() method from Dog class
        myCat.sound(); // Calls the sound() method from Cat class
    }
}