Learn Java for Web Development

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

Now the code of ClassB looks like that shown in Listing A-20.


Listing A-20. Overriding methodA( )


package apress.appendix_A;


public class ClassB extends ClassA {


public void methodA() {
System.out.println("methodA() in ClassB");
}


}


Now both ClassA and ClassB have the same method, methodA().


The following assignment:


ClassA var1 = new ClassB();


confirms that it is possible to call methodA( ) on var1 because ClassA has methodA( ). So, the following
test will compile:


package apress.appendix_A;


public class Test {
public static void main(String[] args) {


ClassA var1 = new ClassB();
var1.methodA();


}
}


Figure A-3. Overriding a method

Free download pdf