我认为我在这里遗漏了一些基本的东西。在编写纸牌游戏应用程序时,我定义了一个 Card 类,然后定义了以下形式的各种纸牌集合:
ArrayList<Card> cards;
现在我当然可以继续使用所有适当的 ArrayList 方法。
有时我厌倦了编写 ArrayList,并且还需要创建 ArrayList 数组,因此定义一个包装类,如下所示:
class CardList {
protected ArrayList<Card> cards;
...overrides and class methods down here...
}
但是现在,当我实例化 CardList(例如 MyCardList)时,我失去了对底层 ArrayList 方法的访问权限,所以看来我可以选择:
(a) 将卡片公开为受包保护的成员,这样我就可以编写 MyCardList.cards.someArrayListMethod() 或
(b) 或在 CardList 中为我想要使用的每个 ArrayList 方法实现直通方法
哪个更好,还是我完全偏离了轨道?
最佳答案
您可以像这样创建一个包范围的类:
class CardList extends ArrayList<Card> {
// Literally no need for anything here unless you want
// constructors that accept capacity, etc.; the default
// constructor will be provided
}
...然后使用它:
CardList list = new CardList();
list.add(new Card());
// ...
<小时/>
但通常最好对接口(interface)进行编码,在这种情况下:
interface CardList extends List<Card> {
// No need for anything here
}
和
class CardListImpl extends ArrayList<Card> implements CardList {
// No need for anything here unless you want constructors
// that accept capacity, etc.
}
并使用它:
CardList list = new CardListImpl();
list.add(new Card());
// ...
...然后你可以切换到LinkedList<Card>
如果您愿意,只需更改一个文件即可。
或者就此而言,您实际上并不需要 CardList
接口(interface)— CardList
只比 List<Card>
短两个字符。所以那就是:
class CardListImpl extends ArrayList<Card> {
// No need for anything here unless you want constructors
// that accept capacity, etc.
}
并使用它:
List<Card> list = new CardListImpl();
list.add(new Card());
// ...
...如果您决定切换具体列表类的类型,您只需在一处执行此操作。
关于java - 使用包装类来实现 Java 中的 typedef 等效项;我必须公开类变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265108/