Java Tutorials
Java Methods
Java Classes
Java File Handling
In Java, it is possible to inherit assets and methods from one class to another. We combine the concept of an inheritance into two categories:
To get an asset from the class, use an extends
keyword.
In the example below, the Car
category (sub-category) inherits the attributes and methods from the Vehicle
class (top category):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Did you notice the protected
modifier in Vehicle?
Set the brand attribute on Vehicle as a protected
access controller. If set to private
, the Car class will not be able to access it.
- Useful for code reuse: re-use the attributes and methods of the existing class when creating a new class.
Tip: Also look at the next chapter, Polymorphism, which uses inherited methods to perform various functions.
If you do not want other classes to inherit the classroom, use the final
keyword:
If you try to access a final
class, Java will generate an error:
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
The output will be something like this:
Main.java:9: error: cannot inherit from final Vehicle
class Main extends
Vehicle {
^
1 error)