Learn Java for Web Development

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

Figure A-4 shows InterfaceA, just to illustrate that the reference type could be an interface or
a class (or abstract class), and the compiler will check the existence of the method against the
reference type of any of these in the similar manner. Listing A-21 implements the hierarchy shown in
Figure A-4.


Listing A-21. Hierachy of Class B


package apress.appendix_A;
public interface InterfaceA {


public void methodA();


}


package apress.appendix_A;
public class ClassA implements InterfaceA{


@Override
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");
}
}


In Listing A-21, the call methodA( ) is verified against reference type InterfaceA, and after checking
that methodA( ) exists in InterfaceA, the compiler approves the call; that is, there is no compile-time
error. Run the test shown in Listing A-22.


Listing A-22. Test Application


package apress.appendix_A;
public class Test {
public static void main(String[] args) {
InterfaceA var1 = new ClassB();
var1.methodA();
}
}


You get the following output:


methodA() in ClassA

Free download pdf