Excluding Object, which has no superclass, every Java class has one and only one direct superclass. That superclass is implicitly Object if no other superclass is specified using the reserved word extends.

If class B extends from class A, then the subclass B inherits the accessible members from the superclass A. Constructors are not inherited but they can be invoked from the subclass constructor using super(…). In fact, a whole chain of constructors starting from the top superclass is invoked when you create an instance of a subclass (see the lesson Class Initialization and Inheritance for more details about this).

Inherited methods can be overridden as is explained below.

Overriding Methods

A superclass instance method (non-static method) is overridden when you write a new instance method in the subclass that has the same signature and return type (or subclass of that type).

If the subclass method has the same signature (method name and parameter type and order) but a different return type then you’ll get a compiler error. There are, however, some changes that you can make in an overriding method:

  • The access modifier can allow more access than the overridden method (but not less)
  • You can make abstract any non-abstract overridden method (and so the subclass will also be abstract)

You can learn more about access modifiers and abstract classes in the lessons about these topics:

The following are examples of valid and invalid method overriding:

Although it’s not shown in the previous example, it’s a good practice use the @Override annotation to tell the compiler that you intend to override a method (and so there will be a compiler error if the method doesn’t exist in one of the super classes):

Inheritance and Exceptions

The following table illustrates how inheritance affects to the exceptions declared in the throws clause of constructors and overriding methods:

  • Must declare all the checked exceptions (or super classes of them) declared in the superclass constructor (Why? Because it’s invoked from the subclass constructor and so it has to be ready to throw at least those)
  • May add other exceptions 
Overriding methods
  • Can throw a subset of the exceptions or sub classes of the exceptions thrown by the overridden method
  • Having no throws clause is also valid since an empty set is a valid subset
  • Warning: a method can throw any RuntimeException (such as a NullPointerException) even without declaring it in its throws clause. This means that RuntimeException and any subclasses of it are always valid as a subset of the exceptions thrown by the overridden method

Below are examples of valid and invalid declarations:

To learn more about exceptions you can read the following lessons:

Leave a Reply