Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - declaring variables in an interface but not assigning them

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?

like image 498
TwoShorts Avatar asked Jun 27 '26 19:06

TwoShorts


2 Answers

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.

like image 109
rgettman Avatar answered Jun 30 '26 09:06

rgettman


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.

like image 32
TTT Avatar answered Jun 30 '26 07:06

TTT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!