继承基于文本的游戏的类

时间:2011-02-22 01:39:31

标签: java class inheritance text adventure

我正在尝试为课程创建一个基于文本的游戏,并且我一直试图让我的主要课程GCPUAPP从我的神器课程中读取。

这是我为GCPUAPP课程输入的代码:

Artifact artifact=new Artifact();
artifact.name="Harry Potter and the Deathly Hallows";
artifact.description="Harry and his friends save the qizarding world again";
r1.contents=artifact;
dialog();

它给了我一个关于“新神器”的错误。这是我在Artifact上的代码:

public abstract class Artifact{ 

    String name, description;

    public String toString(){
        return name;
}

我是Java的新手,所以我完全陷入困境。

3 个答案:

答案 0 :(得分:4)

您无法创建抽象类Artifact artifact=new Artifact();

的实例

这是抽象类的重点。只有继承抽象类的非抽象类才能被实例化为对象。

从类定义中删除abstract表示法,或者创建另一个继承Artifact的类,并将构造函数称为Artifact artifact=new MyNewArtifact();

答案 1 :(得分:1)

您无法创建抽象变量的实例。因此,AbstractClass ac=new AbstractClass()会抛出编译时错误。 相反,您需要从抽象类继承另一个类。 例如:

public abstract class AbstractClassArtifact{ 

    String name, description;

    public String toString(){
        return name;
}

然后使用:

 public class Artifact extends AbstractClassArtifact{
   public Artifact(String name, String description){ //Constructor to make setting variables easier
     this.name=name;
     this.description=description;
   }
 }

最后用:

创建
 Artifact artifact=new Artifact("Harry Potter and the Deathly Hallows", "Harry and his friends save the qizarding world again");
 r1.contents=artifact.toString();
 dialog();

答案 2 :(得分:0)

我会这样做

class HarryPotterArtifact extends Artifact {

    // no need to declare name and desc, they're inherited by "extends Artifact"

    public HarrayPotterArtifact(String name, String desc) {
         this.name = name;
         this.desc = desc;
    }
}

像这样使用:

//Artifact artifact=new Artifact();
//artifact.name="Harry Potter and the Deathly Hallows";
//artifact.description="Harry and his friends save the qizarding world again";

  String harryName = "Harry Potter and the Deathly Hallows";
  String harryDesc = "Harry and his friends save the qizarding world again";
  Artifact artifact = new HarryPotterArtifact(harryName,harryDesc);