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

问题描述

我目前正在使用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:

当我尝试将其声明为以下任意内容时:

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 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();

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

08-22 19:39
查看更多