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

extends

Example

The Car class, as a subclass, acquires the attributes and methods from the Vehicle class, its superclass.

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);
  }
}

Definition and Usage

The “extends” keyword signifies inheritance, indicating that a class derives from another class.

In Java, it’s feasible to inherit attributes and methods from one class to another, with the inheritance concept categorized into two groups.

  • subclass (child): refers to the class that inherits from another class,
  • superclass (parent): denotes the class being inherited from.

To achieve inheritance from a class, utilize the “extends” keyword.