简体   繁体   中英

Java invoke subclass and superclass

public class prelim {
   public static void main(String[] args) {
    A a = new A();
    System.out.println(a.x);
    System.out.println(a.m());
    B b = new B();
    System.out.println(b.x);
    System.out.println(b.m());
    a = new B();
    System.out.println(a.x);
    System.out.println(a.m());
    b = (B)a;
    System.out.println(b.x);
    System.out.println(b.m());
} 
}
class A {
    int x;
    A() { 
         this(1); 
    }
    A(int x) {
             this.x = x; 
    }
    int m() {
             return x; 
    }
}
class B extends A {
     int x;
     B() { 
       this(2); 
     }
     B(int x) {
       super(x+1);
       this.x = super.x + 1;
     }
     int m() {
        return x; 
     }
  }

As for a = new B(); and b = (B)a; What is the type of a and b since it is not declared. And the output was 3 4 4 4. I think a is the type B. So ax and am() should be 4 4.

I don't know exactly the procedure of invoking subclass and its methods.

Variable "a" has type A, which is what it is declared with. The type of the variable never changes. Variables in Java are references. A variable of type A can point to an object of type A or one of its subclasses (or null ).

Likewise variable "b" has type B. It can only point to an object of type B or null since B has no subclasses.

The correct printout (removing linebreaks for brevity) is:

1 1 4 4 3 4 4 4

The types of the objects for the four printouts are

A B B B

In the third printout ax accesses the "x" variable for the A class, which exists, even though the object has class B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM