質問

I am trying to make a shapes class, whose subclasses will be shapes with a constant amount of faces. I want to make this shapes class implement an interface that will ensure that each class implements several constants that will be assigned in the constructor.

public abstract class Shapes{
public static final int edges; 
    public Shapes(int edges) {
        this.edges = edges;
    }
}

public interface Shapeable{
    int edges;
}

this gives me a compile error saying the variable may not be initialized. What should I do instead of this to ensure that all subclasses of shapes implement a variable called edges, but changes with each class?

役に立ちましたか?

解決

You can't force a class to have a variable, but with an interface you can force it to have a method. Change your edges variable in your interface to a method.

public interface Shapeable {
    int getNumEdges();
}

Then implementers must implement the method, but they're free to return any number of edges they want.

他のヒント

Any fields on an interface are automatically public static final. You cannot "implement" a field, that concept does not exist. Interfaces in Java are the definition of the PUBLIC API of a method and thus only contain public method signatures.

I suggest you look into using enumerations or define getters in the interface as rgettman suggests, the constant interface antipattern has way too many downsides. If you do want to use it properly, just look at that link. In short, what the constant interface antipattern really does is just allows for convenient naming of constants in the code. Using a constant interface antipattern is the exact same as using a class with only public static final members, otherwise(and in fact, we have the import static antipattern for this exact purpose, but heed oracle's advice and use sparingly)

Edit:

The reason why you are getting the "not initialized" error is because the field on the interface is, as I said, automatically public static final regardless of what modifiers you place on it. Since you did not initialize the static final field, the compiler complains at you.

You could also make an abstract class instead, and initialize the variable to a nonsense value that the subclasses could then overwrite.

public abstract class Shape{
    int edges = -1;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top