Inheritance in Java

The ability for one class to inherit the characteristics and methods of another class is known as inheritance in object-oriented programming (OOP). A hierarchical class structure is possible in Java by building new classes from existing classes. The class that inherits from the superclass is referred to as the parent class, and the class that inherits from it is referred to as the child class.

Here is how Java handles inheritance:

Superclass (Parent Class):

public class Vehicle {

    String brand;

    int year;

    public void start() {

        System.out.println("Vehicle is starting...");

    }

    public void stop() {

        System.out.println("Vehicle is stopping...");

    }

}

Subclass (Child Class):

public class Car extends Vehicle { int numberOfDoors; public void accelerate() { System.out.println("Car is accelerating..."); } // Additional methods specific to Car }

The Car class is the subclass in this example, with the Vehicle class acting as the superclass. The Car class inherits the methods (start(), stop()) and attributes (brand, year) from the Vehicle class. The Car class also defines its own methods (accelerate()) and attributes (numberOfDoors). Important Java inheritance points:

Access to Superclass Members: The subclass inherits from the superclass all public and protected fields and methods that are accessible. The subclass has no direct access to the superclass's private members. Constructor Inheritance: The super() keyword allows the constructor of a subclass to call the constructor of the superclass. This makes sure that the constructor of the superclass is called before the constructor of the subclass.

Method Overriding: Subclasses have the option of implementing methods that were inherited from the superclass on their own. It's known as method overriding. A method in the subclass is supposed to override a method in the superclass, and this is indicated by the @Override annotation.

Polymorphism: Subclasses can be utilized anywhere objects of the superclass are anticipated due to polymorphism. Because of this, many subclasses may behave polymorphically and be used interchangeably.

Single Inheritance: Java enables single inheritance, which allows a class to derive from just one superclass. This avoids complicated problems brought on by dual inheritance.

Comments

Popular Posts