简体   繁体   中英

Get the right field from an abstract class hierarchy?

I have an Abstract class 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?

In my real program I have an ArrayList of A objects

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?

if you don't override getX() on extended classes you will get x from A.

if you override getX() you will get the value returned on overrides method.

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.

If this method was not overriden on Class B then you will get the value defined on Class A.

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