-1

我正在尝试为班级创建一个基于文本的游戏,但我一直在努力让我的主班 GCPUAPP 从我的 Artifact 班级中读取。

这是我为 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 新手,所以我完全被卡住了。

4

3 回答 3

4

您不能创建抽象类的实例Artifact artifact=new Artifact();

这就是抽象类的意义所在。只有继承抽象类的非抽象类才能被实例化为对象。

abstract从您的类定义中删除符号,或者创建另一个继承Artifact并调用构造函数的类Artifact artifact=new MyNewArtifact();

于 2011-02-22T01:44:14.143 回答
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();
于 2017-07-18T20:38:09.900 回答
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);
于 2011-02-22T05:41:48.923 回答