java继承和多态,对象a = 对象b,调用的是哪个成员变量。
PHPz
PHPz 2017-04-18 10:29:27
0
1
284
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。

PHPz
PHPz

学习是最好的投资!

reply all (1)
小葫芦

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.

Polymorphismis related to methodand has nothing to do with field.
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!