简体   繁体   English

从抽象类层次结构中获取正确的字段?

[英]Get the right field from an abstract class hierarchy?

I have an Abstract class A 我有一个抽象类A

public abstract class A{
    private int x;
    public void doSomethingToX{...};
    public int getX(){
     return x;
    }

I have 7 classes that extend A, each of the 7 implement doSomethingToX in the same way, so I defined it in class A. If class B extends A, and I call B.doSomethingToX(), and then I call B.getX(), will I get B's X value or will I get A's? 我有7个扩展A的类,这7个实现都以相同的方式实现doSomethingToX,因此我在A类中对其进行了定义。如果B类扩展了A,则我调用B.doSomethingToX(),然后又调用B.getX( ),我会得到B的X值还是得到A的值?

In my real program I have an ArrayList of A objects 在我的真实程序中,我有一个A对象的ArrayList

ArrayList<A> list;

and I call: 我打电话给:

  list.add(new B());
   list.get(index).doSomethingToX();
   list.get(index).getX();

Will I get A's x or B's? 我会得到A的x或B的吗?

if you don't override getX() on extended classes you will get x from A. 如果不在扩展类上重写getX(),则将从A获得x。

if you override getX() you will get the value returned on overrides method. 如果重写getX(),则将获取覆盖方法上返回的值。

example: 例:

A a = new B(); a.getX();
B b = new B(); b.getX();

All the above lines will return the value of getX() overridden on Class B. 以上所有行均将返回在B类上覆盖的getX()值。

If this method was not overriden on Class B then you will get the value defined on Class A. 如果未在Class B上重写此方法,则将获得在Class A上定义的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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