Domanda

I have an abstract class "TapeObject" extended by "Wall" and "Gate". Each TapeObject is identified by it's name (set in constructor).

public static TapeObject create(String format) {
    if (format.length() != 1) {
        return null;
    }
    TapeObject tmpobj;
    if (format.equals("w")) {
        return tmpobj = new Wall (this.name);
    }
    if (format.equals("g")) {
        return tmpobj = new Gate (this.name);    
    }
    return null;
}

Why my IDE says "cannot find symbol Wall/Gate" and also "non-static variable name cannot be referenced from a static context"? I'm new to java. How can I create and return the objects properly? The method must remain static.

È stato utile?

Soluzione

You cannot reference class/instance variables from a static method because a static method is not associated with a specific instance of its class. You are referring to name inside a static method, but for example, if I say

MyClass.create() I did this without instantiating an object of type MyClass, so without instantiation, Java does not reserve any space in memory for the name variable

Static methods are meant to be used as helper or util methods.

Also, it is odd that you have a method called create Creation is referred to as instantiation, and it is the job of the constructor to handle this logic.

You can try this in your class that is invoking this create method

TapeObject to1;
if (format == "w") {
  to1 = new Wall("Berlin Wall")
}

Your Wall constructor should be as follows:

public Wall(String name) {
  super(name); // passes the name field to your superclass
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top