search

Home  >  Q&A  >  body text

java继承和多态,对象a = 对象b,调用的是哪个成员变量。

public class Test {
    
    public static void main(String[] args) {
        A a = new A();
        a.s = 11;
        B b = new B();
        b.s = 22;
        a = b;
        System.out.println(a.s);
        System.out.println(b.s);
        System.out.println(a.getS());
        System.out.println(b.getS());
    }
}
class A {
    int s = 1 ;
    int getS() {
        return s;
    }
}

class B extends A {
    int s = 0;
    int getS() {
        return s;
    }
}

输出的是 1 22 22 22
为什么 第一个输出的是1而不是0或者22.按照输出1来看,他调用的是父类A的成员变量s。
这个涉及到了多态,此时a已经指向了men-B,理应输出22,为何输出的是A的成员变量s=1。

PHPzPHPz2911 days ago300

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:31:27

    The member variable called is determined by the "type of the variable".
    A a; If the variable is of type A, it is the variable of type A being called. A a; 变量为A类型就是调用的A类型的变量。
    B b; 变量为B类型就是调用的B类型的变量。
    多态是跟method相关,跟fieldB b; If the variable is of type B, it is the variable of type B being called.

    Polymorphism is related to method and has nothing to do with field. 🎜

    reply
    0
  • Cancelreply