Inheritance

Inheritance

Inheritance is a fundamental concept of object-oriented programming that allows a new class to be based on an existing class. The new class, called the derived class or subclass, inherits the properties and methods of the existing class, called the base class or superclass.

The derived class can then add its own properties and methods, and can also override or modify properties and methods inherited from the base class. This allows for code reuse and can simplify the design and maintenance of complex applications.

In Java, inheritance is implemented using the extends keyword. When a class is declared with the extends keyword, it becomes a subclass of the specified superclass. The subclass inherits all non-private properties and methods of the superclass, and can add its own properties and methods as needed.

For example, consider the following code:

class Vehicle {

   private String make;

   private String model;

   private int year;

   public Vehicle(String make, String model, int year) {

      this.make = make;

      this.model = model;

      this.year = year;

   }

   public String getMake() {

      return make;

   }

   public String getModel() {

      return model;

   }

   public int getYear() {

      return year;

   }

}

class Car extends Vehicle {

   private int numDoors;

   public Car(String make, String model, int year, int numDoors) {

      super(make, model, year);

      this.numDoors = numDoors;

   }

   public int getNumDoors() {

      return numDoors;

   }

}

In this example, the Vehicle class is the superclass, and the Car class is the subclass. The Car class extends the Vehicle class using the extends keyword. The Car class adds a numDoors property that is specific to cars.

The Car class also has a constructor that takes the same parameters as the Vehicle constructor, plus an additional parameter for numDoors. The super keyword is used to call the Vehicle constructor and pass the necessary parameters.

The Car class also has a getNumDoors method that returns the value of the numDoors property. With this inheritance relationship, a Car object can access the getMake, getModel, and getYear methods of the Vehicle class, as well as the getNumDoors method of the Car class. This allows for code reuse and can make the implementation of a complex application more straightforward.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Identity Access Management
Exception handling

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?