如下面例子:

public class A {
    int x=10;
    
    public int getx() {return x;}
}
public class B extends A {
    int x=20;
    
}

public class C {
    public static void main(String[] args) {
        A a=new B();
        System.out.println(a.getx());  //1 
        
        B b=new B();
        System.out.println(b.getx());  //2
    }
}

运行结果如下:

10

10

从上面的两个结果可以看出 不论是a 对像还是b 对像,它所对的B类中都没有getx()方法,我们通过b对像所访问的getx方法都是运行的从父类继承过来的方法,当运行父类的方法时,返回的当然是父类中的x 。

再看下面的例子:

public class A {
    int x=10;
    
    public int getx() {return x;}
}
public class B extends A {
    int x=20;
    
    public int getx() {return x;}
    
}
public class C {
    public static void main(String[] args) {
        A a=new B();
        System.out.println(a.getx());   //1
        
        B b=new B();
        System.out.println(b.getx());
    }
}

运行结果为:

20

20

我们通过第1句System.out.println(a.getx()) 我们看似在调用A类的  getx()方法,其实则不然,我们调用的a对像的实例引用的getx()方法,就是B类的getx方法,B类的getx方法,当然只返回b类的x成员,即20

 

posted on 2017-09-21 00:09  bateman6988  阅读(218)  评论(0编辑  收藏  举报