Learn Java for Web Development

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






  1. package apress.appendix_A;



  2. public class ClassB extends ClassA {





  3. }


Listing A-16 is a driver class for testing the inheritance in Listing A-15.


Listing A-16. Testing Inheritance


package apress.appendix_A;


public class Test {


public static void main(String[] args) {
ClassB var1 = new ClassB();


var1.method1();
// var1.method2(); // private method not Inherited


ClassB.method3();// static method


}


}


Listing A-16 illustrates that even if there are no methods defined in ClassB, methods of ClassA are
available in ClassB and can be invoked on the reference variable where the actual object type is of
ClassB. Line 9 shows that private methods are not inherited.


Here is the output:


classA - method1


classA - method3


Constructor Chaining


When a subclass is instantiated by invoking one of its constructors, the constructor first calls the
no-argument constructor of the superclass. In the superclass, the constructor also calls the constructor
of its superclass. This process repeats itself until the constructor of the java.lang.Object class
is reached. In other words, when you create an object of a subclass, all its superclasses are also
instantiated. Listing A-17 illustrates this constructor chaining.

Free download pdf