Learn Java for Web Development

(Tina Meador) #1
APPENDIX A: Introduction to Java 393

The output proves that the constructor of the subclass invokes the base class’s no-arg constructor.
The Java compiler changed ClassB’s constructor to the following:


public ClassB(String title) {
super();
System.out.println("Class B constructor ");
}


The keyword super represents an instance of the direct superclass of the current object. Since super
is called from an instance of subclass, super represents an instance of ClassA. You can explicitly
call the parent’s constructor from a subclass’s constructor by using the super keyword, but super
must be the first statement in the constructor. Using the super keyword is handy if you want another
constructor in the superclass to be invoked.


public ClassB(String title) {
super(title);
System.out.println("Class B constructor ");
}


Polymorphism


Polymorphism is one of the most important principles of OO programming and as such is the heart
of OOP. Polymorphism refers to how an object in Java can take on many forms. To understand
how polymorphism works in Java, let’s look at an example of a class that extends another class
(see Figure A-2).


Figure A-2. Extending a class

Free download pdf