Java Tutorial – 13 – Inheritance

Inheritance enables a class to reuse code
from another class. In this example we have the class Apple that inherits from Fruit,
specified by 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 now gains all accessible
members in Fruit, except for its constructors. The other members seen here all come from
the root class Object. A class in Java may only inherit from one
superclass and if we don’t specify a one, it will implicitly inherit from Object.
Conceptually, a subclass is a specialization of the superclass. This means that Apple here
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 we create an instance of Apple we can upcast it to Fruit
since the subclass contains everything in the superclass. The Apple is now seen as a Fruit so we can
only access the Fruit members. When we then downcast the class back into an Apple the
fields specific to Apple remains unchanged, because the Fruit only encapsulated the Apple
it did not convert it. The downcast has to be made explicit since downcasting an actual
Fruit into a Apple is not allowed. We can test to see if an object can be cast
to a class using the instance of operator. This operator returns true if the left side
object can be cast into the right side type without causing an exception.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *