Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Inheritance

Java Inheritance (Subclass and Superclass)

In Java, inheriting attributes and methods from one class to another is achievable. We categorize the “inheritance concept” into two groups:

  • Subclass (child): The class inheriting from another class.
  • Superclass (parent): The class being inherited from.

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):

Example

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 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.

The final Keyword

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:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}

The output is typically in this format:

Main.java:9: error: cannot inherit from final Vehicle

class Main extends Vehicle {

                  ^

1 error)