如何正确声明子类的实例?
我目前正在使用 Java 进行基于文本的冒险,目的是使用它作为测试平台,尝试我从正在阅读的这本 Java 书中学到的新东西。
我现在尝试声明一个子类的实例(因为玩家编写了脚本来查找它)。 父类是 Item
,它有两个子类:Weapon
和 Armour
。
但是,无论我尝试以哪种方式声明它,我正在使用的 IDE (Eclipse) 都会将该行标记为以下错误:
没有可访问的 Item 类型的封闭实例。必须使用 Item 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 Item 的实例)。
当我尝试像以下任何一个一样声明它时:
Item machinePistol = new Weapon();
Weapon machinePistol = new Weapon();
Item machinePistol = new Item.Weapon();
Weapon machinePistol = new Item.Weapon();
作为参考,项目类看起来像这样:
package JavaAIO;
public class Item
{
public String itemName;
public double itemWeight;
public class Weapon extends Item
{
public double damage;
public double speed;
}
public class Armour extends Item
{
public double dmgResist;
public double attSpdMod;
}
}
所以如果有人可以告诉我如何正确实例化武器(这样我就可以设置其字段的值并将其提供给玩家) ),我将不胜感激。
I am currently making a text based adventure in Java for the purposes of using it a test platform, to try out new things I learn from this Java book I'm reading.
I am now trying to declare an instance of a subclass (as the player is scripted to find it).
The parent class is Item
and it has two subclasses: Weapon
and Armour
.
However, no matter which way I try and declare it in, the IDE I'm using (Eclipse) flags the line with the following error:
No enclosing instance of type Item is accessible. Must qualify the allocation with an enclosing instance of type Item (e.g. x.new A() where x is an instance of Item).
When I attempt to declare it like any of the following:
Item machinePistol = new Weapon();
Weapon machinePistol = new Weapon();
Item machinePistol = new Item.Weapon();
Weapon machinePistol = new Item.Weapon();
For reference the item class looks like this:
package JavaAIO;
public class Item
{
public String itemName;
public double itemWeight;
public class Weapon extends Item
{
public double damage;
public double speed;
}
public class Armour extends Item
{
public double dmgResist;
public double attSpdMod;
}
}
So if anyone could tell me how I could properly instantiate a Weapon (so I can set the values of its fields and give it to the player), I would greatly appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是非常不言自明的:
或者:
但是,我强烈建议将它们放在自己的类中,以便您最终可以得到:
It's pretty self-explaining:
Or:
However, I strongly recommend to put them in their own classes so that you can end up with:
为此:
您需要将内部类声明为静态:
或者另一个(也是更好的)选择是不将它们设为内部类:
然后您可以将它们设为这样;
To do this:
you would want to declare your inner classes as
static
:Or another (and better) option is to not make them inner classes:
Then you can make them like this;
您不应在
Item
内声明Weapon
和Armour
类。只需在外部声明它们即可:这样您就可以像这样实例化它们:
You shouldn't declare the classes
Weapon
andArmour
insideItem
. Just declare them outside:So you can instantiate them like this: