Logout

Inheritance

Inheritance is the third of the "big three" OOP concepts, along with encapsulation and polymorphism. You could argue that inheritance is not necessarily dependent on the object oriented approach, but it is more closely associated to it than polymorphism. Inheritance works well with the making of "template" classes. Still, inheritance as a concept on its own is not tied only to the OOP approach.

In general, what the concept of inheritance gives programming languages is the ability to take existing concepts and classes, and expand upon them, without having to re-invent the wheel. At one level, it can offer ideas of how certain kinds of classes can be created. A Java interface is just that; not an actual functional class; rather an idea of a class with suggested empty methods that can be overriden for certain kinds of tasks. But the type of inheritance that the IB program would have you do is taking an actual class (not just an interface), and extending it to new class, which uses all of the methods (and therefore attributes) of the class which it is extending.

The two keywords you'll need for doing this are extends to be put in the class heading to let the computer know which class is being used as the super-class, and the keyword super which calls the constructor of the super class from within its own constructor.


public class Car extends MotorVehicle{
    
    private int numSeats = -999;
    private boolean isOpenRoof = false;

    public Car(){

    }

    public Car(boolean isElectrical, int numWheels, int numSeats, boolean isOpenRoof){
        super(isElectrical, numWheels);
        this.numSeats = numSeats;
        this.isOpenRoof = isOpenRoof;
    }
}

REFER TO the full image of the inheritance system that we did in class.
And note in that diagram how, at the bottom when we type in the object of our Car class, a bunch of methods come up, most of which are not in Car, but from the other classes we inherited stuff from.


For us, the best example of a large inheritance system of the GUI elements we have been using.

Here's part of it:

So the best place to look here would be our good old friend JTextField. Every time we make a textField in our GUI, we are making an instance (or actually, it's Netbeans doing it behind the scenes in the generated code) of a class which extends a class called JTextComponent, which, in turn is a class which extends a class called JComponent, which extends the mother of all classes, Object.

So everything that Object, and JComponent, and JTextComponent can do, JTextField can do too, along with a number of other methods of its own. It, in turn, is used as the super class for JPassowordField.