如何正确声明子类的实例? [英] How do I properly declare an instance of a subclass?

查看:108
本文介绍了如何正确声明子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Java进行基于文本的冒险,目的是将其用作测试平台,以尝试从我正在阅读的Java书籍中学到的新知识.

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.

我现在正在尝试声明一个子类的实例(因为播放器已编写脚本来查找它). 父类是Item,它具有两个子类:WeaponArmour.

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.

但是,无论我尝试使用哪种方式对其进行声明,我正在使用的IDE(Eclipse)都使用以下错误标记该行:

However, no matter which way I try and declare it in, the IDE I'm using (Eclipse) flags the line with the following error:

无法访问类型为Item的封闭实例.必须使用一个封闭的类型为Item的实例来限定分配(例如x.new A(),其中x是Item的实例).

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.

推荐答案

无法访问类型为Item的封闭实例.必须使用类型为(例如xx是Item的实例)的封闭实例来限制分配."

这很不言自明:

Item machinePistol = new Item().new Weapon(); 

或者:

Item item = new Item();
Item machinePistol = item.new Weapon(); 

但是,我强烈建议将它们放在自己的类中,以便最终使用:

However, I strongly recommend to put them in their own classes so that you can end up with:

Item machinePistol = new Weapon();

这篇关于如何正确声明子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆