News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 13 – Inheritance

Inheritance allows a class to acquire the members of another class. In the example below, Apple inherits from Fruit. This is specified with the extends keyword. Fruit then becomes the superclass of Apple, which in turn becomes a subclass of Fruit. In addition to its own members, Apple gains all accessible members in Fruit, except for its constructors.

// Superclass (parent class)
class Fruit
{
  public String flavor;
}
 
// Subclass (child class)
class Apple extends Fruit
{
  public String variety;
}

Object

A class in Java may only inherit from one superclass, and if no class is specified it will implicitly inherit from Object. Therefore, Object is the root class of all classes.

class Fruit extends Object {}

Upcasting

Conceptually, a subclass is a specialization of the superclass. This means that Apple is a kind of Fruit, as well as an Object, and can therefore be used anywhere a Fruit or Object is expected. For example, if an instance of Apple is created, it can be upcast to Fruit since the subclass contains everything in the superclass.

Apple a = new Apple();
Fruit f = a;

The Apple is then seen as a Fruit, so only the Fruit members can be accessed.

f.flavor = "Sweet";

Downcasting

When the class is downcast back into an Apple, the fields that are specific to Apple will have been preserved. This is because the Fruit only contained the Apple, it did not convert it. The downcast has to be made explicit since downcasting an actual Fruit into an Apple is not allowed.

Apple b = (Apple)f;

Instanceof operator

As a safety precaution, you can test to see whether an object can be cast to a specific class by using the instanceof operator. This operator returns true if the left side object can be cast into the right side type without causing an exception.

Apple c = (f instanceof Apple) ? (Apple)f : null;
Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours