inheritance

Inheritance is a fantastic feature which simplifies development and facilitates reuse of classes. A class can inherit properties and methods from another class. The inheriting class is called the subclass while the class it is inheriting from is called the superclass. subclasses have the option to add new methods and properties as well as modify the functionality of existing methods if needed. To inherit from another class, we need to use the extends keyword.

Buses, cars and trucks are all vehicles. They all have wheels, doors, brakes, etc. Instead of defining all these properties of every kind of vehicle, we can define a class vehicle that would define all the properties. The subclasses Car and Truck will only modify what is needed define a car. Following is the superclass Vehicle.java

public class Vehicle {
   int wheels;<br><br>   
   
   Vehicle() {<br>       
      this.wheels = 4;<br>   
   }<br><br>   

   public void setWheels(int w) {     
      this.wheels = w;
   }

   public void getParameters() {
      System.out.println(this.wheels);
   }

   public void print() {       
      System.out.println("has " + this.wheels + " wheels.");   
   }
}

and subclass Car

public class Car extends Vehicle {
   // will work without any code here
}

and the test class

public class testVehicles {
   public static void main(String[] args) {
      Car c = new Car();
      c.getParameters();
   }
}

testVehicles() instantiates a Car object and calls getParameters(). Car is an empty class with no methods defined. Yet it prints results because it extends the class Vehicle. Vehicle defines the method getParameters(). The result we see comes from the class Vehicle.

By master