In Java, inheriting attributes and methods from one class to another is achievable. We categorize the “inheritance concept” into two groups:
To implement inheritance from a class, employ the extends keyword.
In the following example, the Car class (subclass) inherits attributes and methods from the Vehicle class (superclass):
class Vehicle {
protected String brand = “Ford”; // Vehicle attribute
public void honk() { // Vehicle method
System.out .println(“Tuut, tuut!”);
}
}
|
Did you observe the use of the protected modifier in the Vehicle class? The brand attribute in the Vehicle class is configured with a protected access modifier. If it were set to private, the Car class would be unable to access it. When and Why to Utilize “Inheritance”? Employing inheritance enhances code reusability by allowing you to inherit attributes and methods from an existing class when defining a new class. Tip: Be sure to check out the next chapter, Polymorphism, which demonstrates how inherited methods can be used to perform various tasks. |
When you wish to prevent other classes from inheriting from a particular class, employ the final keyword.
If you try to access a final class, Java will generate an error:
|
The output is typically in this format:
Main.java:9: error: cannot inherit from final Vehicle class Main extends Vehicle { ^ 1 error) |