Java Inheritance

www.igi‮.aeditf‬com

In Java, inheritance is a mechanism that allows a class to inherit properties and methods from another class. The class that is being inherited from is called the superclass or parent class, and the class that inherits from the superclass is called the subclass or child class.

To inherit from a superclass in Java, you use the extends keyword in the subclass definition, followed by the name of the superclass. The subclass automatically inherits all the properties and methods of the superclass, including any public or protected fields or methods.

Here's an example of using inheritance in Java:

class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void speak() {
        System.out.println("I am an animal.");
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    public void speak() {
        System.out.println("Woof! My name is " + super.name + ".");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal("George");
        myAnimal.speak(); // prints "I am an animal."
        
        Dog myDog = new Dog("Rufus");
        myDog.speak(); // prints "Woof! My name is Rufus."
    }
}

In the example above, the Dog class extends the Animal class, which means it inherits the name field and the speak() method from the Animal class. The Dog class also overrides the speak() method to provide a unique implementation. The super keyword is used to access the name field in the Animal class from the Dog class.

Inheritance is a powerful feature in Java that allows you to reuse code and create hierarchical relationships between classes. However, it's important to use inheritance carefully to avoid creating complex class hierarchies that are difficult to understand and maintain.