Understanding Class Inheritance in Java


Java supports single inheritance, allowing a class to inherit properties and methods from another class using the extends keyword.

Source Code

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

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class TestInheritance {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat(); // From Animal class
        myDog.bark(); // From Dog class
    }
}

Inheritance promotes code reuse and establishes a relationship between the superclass (parent) and subclasses (children), embodying an “IS-A” relationship.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments