[英]How do I create some objects to store in an arrayList, which is a attribute of sub class, from a parent class in Java?
So I have 3 classes, Lair, LairLocation & Minion. 所以我有3个班,Lair,LairLocation&Minion。 I created an ArrayList, which is supposed to store Minion objects, and this is an attribute of LairLocation.
我创建了一个ArrayList,它应该存储Minion对象,这是LairLocation的一个属性。 I'm supposed to create some objects to store in ArrayList, from the parent class Lair.
我应该从父类Lair创建一些存储在ArrayList中的对象。 Both LairLocation and Minion and sub-classes of Lair.
LairLocation和Minion以及Lair的子类。
Whenever I try to create objects to store in ArrayList form my parent, I keep getting an error saying 'minion cannot be resolved' and telling me to create a local variable etc. Please help 每当我尝试创建存储在我父母的ArrayList中的对象时,我就会收到一条错误,说'minion无法解决'并告诉我创建一个局部变量等。请帮忙
LairLocation
'''
public class LairLocations extends Lair
{
public static ArrayList<Minion> minions = new ArrayList<Minion>();
}
'''
Lair
'''
public class Lair
{
public void createMinions()
{
minions.add("12", "Mine", "Me");//This is giving me the error
}
}
'''
Minion
'''
public class Minion extends Lair
{
private String id;
private String fName;
private String lName;
public Minion(String Id, String fName, String lName)
{
this.id = id;
this.fName = fName;
this.lName = lName;
}
}
'''
You're trying to access a field of a subclass from its parent class. 您正在尝试从其父类访问子类的字段。 This does not work this way.
这不起作用。
You can only access fields of a parent class (if they're public or protected). 您只能访问父类的字段(如果它们是公共的或受保护的)。
So, you either have to move your minions
field to the parent class Lair
(and make it non-static, by the way), or access this object via LairLocation class: LairLocation.minions()
(if the field is supposed to be static). 所以,你要么必须将你的
minions
字段移动到父类Lair
(并且顺便使它成为非静态的),或者通过LairLocation类访问该对象: LairLocation.minions()
(如果该字段应该是静态的) )。
Also, this line of code is incorrect: minions.add("12", "Mine", "Me");
此外,这行代码不正确:
minions.add("12", "Mine", "Me");
The add()
method accepts only one element. add()
方法只接受一个元素。
It should probably be: minions.add(new Minion("12", "Mine", "Me"));
应该是:
minions.add(new Minion("12", "Mine", "Me"));
你必须调用new Minion()
来获得一个新的奴才。
minions.add( new Minion( "12", "Mine", "Me") );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.