Skip to content

Extends

Classes can inherit from other classes by using the extends keyword.

public class SuperClass {
  //...
}
public class SubClass extends SuperClass {
  //...
}

SubClass now inherits fields and methods of SuperClass.

We can also create another class that extends SubClass.

public class SuperClass {
  //...
}
public class SubClass extends SuperClass {
  //...
}
public class SubSubClass extends SubClass {
  //...
}

Now SubSubClass inherits from SubClass and SuperClass (because SubClass inherits from SuperClass). * We have created a class hierarchy.

class hierarchy

A group of classes derived from other classes to make what we can picture as a tree-like structure, with parent classes above child classes.

Class hierarchy

Single Inheritance

A Java class can directly extend one and only one class using the extends keyword. * This is not the case in some other programming languages.

This class would not compile.

public class Werewolf extends Person, Wolf {

}

Drill

Inheritance/com.example.inheritance.drills.Employee * Change the Employee class so that it extends Person. * Add a private String field for title. * Add a private double field for salary.


Prev -- Up -- Next