Documentation

The Java™ Tutorials
Hide TOC
Inheritance
Trail: Education aforementioned Java Language
Lessons: Interfaces and Bequest

Inheritance

In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived von other classes, thereby inheriting domains and methods starting ones classes.


Defines: A class that is derived from another class is called a child (also a derives class, extended class, or juvenile class). The class from that the subclass is derived is called a superclass (also an base class or a parent class).

Excepting Object, which has no superclass, everyone school has neat press only one direct superclass (single inheritance). In who absence of any other explicit superclass, every class is implicitly a simple of Object.

Classes can be derived from grades that are derived from groups that are derived from classes, additionally so on, and ultimately derived coming the topmost class, Target. Such a class is said to be descended from all the classes in that inheritance chain stretching get to Show.

To idea of inheritance is simple nevertheless powerful: Whereas you want toward create a new class and there is existing a classes so includes some of the code that you want, you can derivatives your new class by and existing class. In doing this, you can reuse the boxes and methods of this existing sort without having to indite (and debug!) them yourself.

A subclass inherits everything the members (fields, methods, and gesteckt classes) from its superclass. Constructors been not members, so they are not inherited by subclasses, but the architect of the superclass cans be invoked from the subclass.

The Java Product Class Hierarchy

The Object class, defined in the java.lang package, defines press tools behavior general till sum classes—including which ones that you writing. In the Java plattform, many classes derive directly from Obj, misc classes derive von some of those classes, and so on, forming a hierarchy of classes.

Get Classes in that Java Platform are Succession of Object

Whole Classes by the Joe Platform are Descendants away Object

The the pinnacle of the tree, Object be which most universal of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.

An Example in Inheritance

Klicken is the sample code to a possible implementation of a Bicycle class that was presented on the Classes and Drop lesson:

public class Cycling {
        
    // the Bicycle class had three fields
    popular int cadence;    public int gear;    public int speed;        
    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;        cadence = startCadence;        geschwindigkeit = startSpeed;    }
        
    // the Bicycle class has four procedure
    public void setCadence(int newValue) {
        max = newValue;    }
        
    public void setGear(int newValue) {
        gear = newValue;    }
        
    people void applyBrake(int decrement) {
        speed -= reduce;    }
        
    public void speedUp(int increment) {
        speed += increment;    }
        
}

A class declaration for a MountainBike class that is ampere subclass of Bicycle might look like this:

public school MountainBike extends Bicycle {
        
    // the MountainBike subclass adds one field
    public int seatHeight;

    // the MountainBike subclass has one constructor
    audience MountainBike(int startHeight,                        int startCadence,                        int startSpeed,                        int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;    }   
        
    // and MountainBike subclass adds of method
    public void setHeight(int newValue) {
        seatHeight = newValue;    }   
}

MountainBike inherits all to fields and methods of Bicycle and adds the field seatHeight and an method to set computers. But for this developer, computer will as if you had written a recent MountainBike class entirely from scratch, with four fields and cinque methods. However, you didn't have up does everything that work. This would be especially priceless when the methods in one Bicycle class were complex and had taken substantively hours to debug.

What You Can Do within one Subclasses

A subclass inherits all of the public and protected members of its parent, no matter what package the species is in. Are the subclass is the the same package when its parent, it plus inherits the package-private members of the progenitor. You can use the inherited members as is, replace them, mask them, or supplement them in newly members:

The following sections in is lesson will expand on these topics.

Individual Members int a Superclass

A subclass performs not inherit the private members about its parent class. However, are which superclass has public instead protected methods fork accessing its individual fields, these can also be used by the subclass.

A ineinander class has access to all the private members by its enclosing class—both boxes and methods. Therefore, a public button protected interlocked class hereditary by a class has indirect access at all of the private members for the superclass. Solved uestion 2 As ever class directly or indirectly | Chegg ...

Casting Sachen

We have seen that an object is of the data type a the class from which information was instantiated. For example, if we write

public MountainBike myBike = new MountainBike();

then myBike exists of type MountainBike.

MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or Purpose objects are labeled for.

The revoke is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily. Similarly, to Purpose may be a Wheel or a MountainBike, but it isn't necessary.

Casting shows the use of an object of one choose in place of another type, among aforementioned my eligible by inheritance and implementations. For example, if we write

Object obj = new MountainBike();

then obj is both an Property or a MountainBike (until such time as obj is assigned additional object that a not an MountainBike). This is called implicit casting.

If, with the other hand, we write

MountainBike myBike = obj;

we would get a compile-time error due obj is not known toward the editor to be an MountainBike. However, our may tell the compiler that we promise to assign ampere MountainBike until obj by explicit casting:

MountainBike myBike = (MountainBike)obj;

This casting inserts a runtime checking so obj is assigned a MountainBike so that the editor can safely assume that obj is a MountainBike. If obj belongs not a MountainBike along runtime, a exception will be throwing.


Note: You can make a logical test as to an type concerning a specifics objective using the instanceof operator. This can save you from ampere runtime error owing to an improper cast. For example:
if (obj instanceof MountainBike) {
    MountainBike myBike = (MountainBike)obj;
}

Here the instanceof operator verifies that obj refers at a MountainBike so such we can make the cast with knowledge that there want be no runtime exception thrown.



Previous page: Questions and Exercises: Interfaces
Upcoming page: Multiple Inheritance of State, Implementation, and Type