© Mikael Olsson 2018
Mikael OlssonJava Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-3441-9_12

12. Inheritance

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, Finland
 

Inheritance allows a class to acquire the members of another class. In the following example, 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:

// Same as class Fruit {}
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 because 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. That’s because the Fruit only contained the Apple—it didn’t convert it. The downcast has to be made explicitly using the Java casting format because downcasting an actual Fruit object into an Apple isn’t 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:

boolean b = (f instanceof Apple);
if (b == true)
  Apple c = (Apple)f;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.211