Inheritance in java

Inheritance is a fundamental concept in object-oriented programming that allows a new class to be based on an existing class. In Java, a class can inherit the properties and behaviors of another class using the extends keyword.

The class that is being inherited from is called the superclass or parent class. The class that is inheriting is called the subclass or child class. The subclass can add its own properties and behaviors, or override the properties and behaviors of the superclass.

Here is an example of a superclass in Java:

public class Vehicle {
    String make;
    String model;
    int year;

    public void start() {
        // code to start the vehicle
    }

    public void stop() {
        // code to stop the vehicle
    }
}

Here is an example of a subclass that inherits from the Vehicle class:

public class Car extends Vehicle {
    String color;

    public void accelerate() {
        // code to accelerate the car
    }
}

In this example, the Car class inherits the make, model, and year fields, as well as the start and stop methods, from the Vehicle class. It adds its own color field and accelerate method.

The extends keyword is used to indicate that Car is a subclass of Vehicle. The subclass can access the fields and methods of the superclass using dot notation, like this:

Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
myCar.color = "red";
myCar.start();
myCar.accelerate();
myCar.stop();

In addition to inheriting properties and behaviors, a subclass can also override the methods of the superclass. This allows the subclass to customize the behavior of the method for its own purposes. Here is an example:

public class Car extends Vehicle {
    String color;

    public void start() {
        // code to start the car in a specific way
    }

    public void accelerate() {
        // code to accelerate the car
    }
}

In this example, the start method of the Car class overrides the start method of the Vehicle class, and provides a specific implementation for starting the car.

In conclusion, inheritance is a powerful concept in Java that allows a subclass to inherit the properties and behaviors of a superclass. It enables code reuse, improves code organization, and facilitates polymorphism. A subclass can add its own properties and behaviors, or override the properties and behaviors of the superclass.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in