简体   繁体   中英

Abstract Class Hold Member Field or Use Getter() of Concrete Implementation?

One OOP principle I'm struggling with is Abstract Classes and their ability to hold member fields (variables).

Take for instance the following code ( example 1 ):

public abstract class AbstractClassConstructor {

    List mList;

    public AbstractClassConstructor(List list) {
        mList = list;
    }

    public Object getListRow(int row) {
        return mList.get(row);
    }
}

And please inspect this alternative code which provides the same functionality ( example 2 ):

public abstract class AbstractClassGetter {

    public abstract List getList();

    public Object getListRow(int row) {
        return getList().get(row);
    }
}

I'm concerned with whether example 1 or example 2 is more maintainable, as well, I would like to follow OOP standards as close as possible.

Currently I see more coupling in example 1 than I do example 2, though I don't see many other issues. Example 2 however is more straight-forward, I like that the concrete implementation holds the private field and the AbstractClassGetter uses a method to fetch it. This feels better, but I'm struggling to apply the correct OOP principle to help me know which IS better from this perspective.

As for me, example 1 would not be ideal if mList will be used in the child class with mList 's function that is specific to its type (eg LinkedList or ArrayList). This is because it might need to be cast to its actual type before it could get used. In this case example 2 would be better.

If there's no function of specific type needed in the child class, then example 1 would be better in term of encapsulation.

Updated

Another approach, where perhaps could be considered the middle ground is to use Generic.

public abstract class AbstractClassConstructor<T extends List> {

    T mList;

    public AbstractClassConstructor(T list) {
        mList = list;
    }

    public Object getListRow(int row) {
        return mList.get(row);
    }
}

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