Java Tutorial-Java Inheritance

Java Inheritance


In Java, we can inherit attributes and methods from one class to another. We group “inheritance concept” into two categories:


  • subclass(child) -  the class that inherits from another class
  • superclass(parent) – the class being inherited from

To inherit from a class, use the extends keyword.


Example


In the below example, we inherit Car class from the vehicle class as shown below:


Vehicle.java

public class Vehicle {
       protected String brand = "Volkswagen";
       public void speed(){
              System.out.println("High speed!");
       }
}

Car.java

class Car extends Vehicle {
       private String modelname = "Pasat";
       public static void main (String args[]){
              Car myCar = new Car();
              myCar.speed();
             
              System.out.println(myCar.brand +" "+myCar.modelname);
       }
}

Output

High speed!
Volkswagen Pasat

Example Explained


  • In Vehicle class, we the attribute brand is declared protected, hence it can be inherited to the sub class. If it is declared private, it cannot be inherited to its sub class.
  • The Car class has been inherited from the Vehicle Class. The Atrribute modelname has been declared private, hence this attribute cannot be inherited to its subclasses.


Why Inheritance?


It is mainly used for code reusability: we can reuse the attributes and methods of an existing class to its sub classes.



·