Understanding Inheritance in Java: Principles and Code Demonstration

·

Inheritance is a core concept of Java’s object-oriented programming. It allows one class to inherit fields and methods from another, promoting code reuse. The class that inherits is called the subclass, while the class being inherited from is the superclass.

Here’s an example of inheritance:

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

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

In this example, the `Dog` class inherits the `sound` method from the `Animal` class but overrides it to provide a more specific behavior. Inheritance helps create a hierarchical relationship between classes, enabling polymorphism and code extension.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *