Inheritance and Overriding

Overview

Objects are instances of classes. Objects enclose an environment of instance variables. The instance methods access and modify their own particular instance variables.

A subclass inherits from its superclasses. All classes in Java are subclasses of the ultimate superclass java.lang.Object. A class inherits from its superclasses and extends the class with new instance variables and instance methods.

Examples:

The details:

If the subclass defines fields with the same name as fields in the superclass, the new definition shadows the old definition. If the class defines methods with the same signature as methods in the super class, the new definition overrides the old definition.

Shadowing is not the same as overriding. The type of the reference variable determines which variable resolves hiding. The actual, true type of the object determines which method resolves overriding.

Static (class) methods and fields shadow, rather than override; instance methods override. Static and instance methods cannot attempt to override or shadow one another, although static and instance variables are free to hide one another. Overriding and hiding methods must have the same return type as the overridden or hidden method.

Constructors are not inherited at all.

For a method to override, its signature must be exactly that of the overridden method. Else the method is overloaded, not overridden.