Java Reference
In-Depth Information
Figure A-2 shows a superclass-subclass relationship. This relationship allows you to assign an
object to a reference variable whose type is different from the object type, as follows:
ClassA var1 = new ClassB();
This assigns an object of type ClassB to a reference variable var1 whose reference type is ClassA .
This assignment has different implications at compile time and at runtime. At the compile time,
since the type of the var1 is ClassA , the compiler will not allow calling a method on var1 , which is not
in ClassA , even if that method is in ClassB . Listing A-18 shows the code implementation of Figure A-2 .
Listing A-18. Inheritance
package apress.appendix_A;
public class ClassA {
public void methodA() {
System.out.println("methodA() in ClassA");
}
}
package apress.appendix_A;
public class ClassB extends ClassA {
public void methodB() {
System.out.println("methodB() in ClassB");
}
}
Listing A-19 illustrates the test.
Listing A-19. Driver for Listing A-18
package apress.appendix_A;
public class Test {
public static void main(String[] args) {
ClassA var1 = new ClassB();
// var1.methodB(); uncommenting this code will result in compile time
// error
var1.methodA();
}
}
On line 2 of Listing A-19, it is not possible to call methodB() on var1 even if methodB() is ClassB ,
because the reference type of var1 is ClassA and ClassA does not have methodB() .
Now let's consider the case where ClassB overrides methodA() of ClassA (see Figure A-3 ).
Search WWH ::




Custom Search