【问题标题】:Inheriting classes for a text-based game为基于文本的游戏继承类
【发布时间】:2011-02-22 01:39:31
【问题描述】:

我正在尝试为班级创建一个基于文本的游戏,但我一直在试图让我的主要班级 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 新手,所以我完全被卡住了。

【问题讨论】:

    标签: java class inheritance text adventure


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您不能创建抽象变量的实例。所以,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();
      

      【讨论】:

      • 问题是旧的,最后一个操作连接是Feb 22 '11。但我赞成作为好的答案。但是,如果您使用返回的结果,artifact.toString(); 会更相关。
      • 对不起,我没看是多久以前的。我已经对其进行了编辑,因此它现在使用操作对 toString() 的使用
      【解决方案3】:

      我会这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 2013-07-08
        • 2015-09-10
        • 2023-01-08
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多