Java Inheritance
In Java, we can inherit attributes and methods from one class to another. We group “inheritance concept” into two categories:
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
Why Inheritance?
It is mainly used for code reusability: we can reuse the attributes and methods of an existing class to its sub classes.
·