Sobes.tech
Intern

What is inheritance in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance allows creating new classes based on existing ones, inheriting their fields and methods. The new class is called a subclass (or derived class), and the existing one — a superclass (or parent class).

Advantages of inheritance:

  • Code reuse: Eliminates code duplication, as common functionality is defined in the superclass.
  • Extensibility: A subclass can add new fields and methods, as well as override superclass methods.
  • Class hierarchy: Allows organizing classes into logical hierarchical structures.

Example:

class Animal { // Superclass
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal { // Subclass, inherits from Animal
    void bark() {
        System.out.println("Woof woof!");
    }
}

class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat(); // Call method from superclass
        myDog.bark(); // Call method from subclass
    }
}

It is important to remember that Java supports only single inheritance of classes (a class can inherit from only one superclass), but it supports multiple inheritance of interfaces.

What is inheritance in object-oriented programming… - sobes.tech