๐ŸŽ“ A1Learner
๐Ÿ”
0 of 48 lessons completed

Java Inheritance

Inheritance is a way for one class to take fields and methods from another class. The child class gains the parent code and can add code of its own.

Fields and methods arrive from the parent

Dog extends Animal. The Dog object uses a field and a method that are defined in Animal.

public class Main {
  public static void main(String[] args) {
    Dog dog = new Dog();
    System.out.println(dog.name);
    dog.eat();
  }
}
class Animal {
  protected String name = "Buddy";
  void eat() {
    System.out.println("The animal eats");
  }
}
class Dog extends Animal {
}

The child adds its own method

Dog adds a bark method. The Animal class has no such method.

public class Main {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.eat();
    dog.bark();
  }
}
class Animal {
  void eat() {
    System.out.println("The animal eats");
  }
}
class Dog extends Animal {
  void bark() {
    System.out.println("Woof");
  }
}

Each child object holds its own field value

The name field comes from Animal. Each Dog object stores a separate value in that field.

public class Main {
  public static void main(String[] args) {
    Dog first = new Dog();
    Dog second = new Dog();
    first.name = "Rex";
    second.name = "Luna";
    System.out.println(first.name);
    System.out.println(second.name);
  }
}
class Animal {
  protected String name = "Buddy";
}
class Dog extends Animal {
}

Example

public class Main {
  public static void main(String[] args) {
    Car car = new Car();
    System.out.println(car.brand);
    car.drive();
    car.honk();
  }
}
class Vehicle {
  protected String brand = "Ford";
  void drive() {
    System.out.println("The vehicle drives");
  }
}
class Car extends Vehicle {
  void honk() {
    System.out.println("Beep");
  }
}

Key points

  • A child class uses the extends keyword to inherit from a parent class.
  • The child class gains the fields and methods of the parent class.
  • A protected field in the parent class can be read inside the child class.
  • A child class can add fields and methods of its own.
  • Code written once in the parent class serves every child class.

In this example, Car extends Vehicle. The brand field and the drive method come from Vehicle. Car adds a honk method of its own. The output shows the inherited field, the inherited method, and the added method in order.

Note

A class can extend only one parent class in Java.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the extends keyword do?