Inheriting classes for a text-based game

477 views Asked by At

I'm trying to create a text-based game for class and i'm stuck on trying to get my main class, GCPUAPP, to read from my Artifact class.

Here's the code i've inputed for the GCPUAPP class:

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

It's giving me an error on "new Artifact". Here's the code I have on Artifact:

public abstract class Artifact{ 

    String name, description;

    public String toString(){
        return name;
}

I'm new to Java so I am completely stuck.

3

There are 3 answers

0
ZolaKt On

You can't create an instance of an abstract class Artifact artifact=new Artifact();

That is the point of abstract classes. Only non-abstract classes that inherit the abstract class can be instanced as object.

Either remove the abstract notation from your class definition, or create another class that inherits Artifact and call the constructor as this Artifact artifact=new MyNewArtifact();

0
corsiKa On

I'd do this

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

Use it like this:

//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);
2
AudioBubble On

You can't create an instance of an abstract variable. So, AbstractClass ac=new AbstractClass() would throw a compile-time error. Instead, you need another class to inherit from the abstract class. For example:

public abstract class AbstractClassArtifact{ 

    String name, description;

    public String toString(){
        return name;
}

Then use:

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

Finally create with:

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