: class Parent {
:
String s = "Parent";
: void aMethod() {
: System.out.println("Printing Parent");
: }
: }
: class Child extends Parent {
: String s = "Child";
: void aMethod() {
: System.out.println("Printing Child");
: }
: void childOnlyMethod() {
: System.out.println("Child Only");
: }
: }
: class
Test {
: public static void main(String[] args) {
: Parent p = new Child();
: A: System.out.println(p.s);
: B: System.out.println(p.aMethod()); C: System.out.println(
: ((Child)p).childOnlyMethod());
: }
: }
: Label A: will display "Parent"
: Label B: will display "Printing Child"
: Label C: will display "Child Only"
: Reference type(Parent) determines which version of
: variable referred and object type(Child) referred
: by the reference determine which vesion of
: method invoked. Why so?
And why is this rule: not work for accessing "childOnlyMethod()"
: by simple p.childOnlyMethod() without casting?