To create kits that players can choose, I have made an interface:
public interface Kit {}
And I have implemented it for each kit:
public class Ninja implements Kit {}
Now, I want to set some constants related to the class, not the instance. I want these to be static across all implementations of the interface, and I want each implementation to override them.
Try #1:
public interface Kit {
String DISPLAY_NAME;
// The blank final field DISPLAY_NAME may not have been initialized
}
Try #2:
public interface Kit {
static String getDisplayName();
// Illegal modifier for the interface method getDisplayName; only public & abstract are permitted
}
An interface can not hold data the way a class can hold a field. If you do not want your
Kit
to be instantiated, you most likely want an abstract class. See them as an interface that can have some implementation and fields.Note, please read for further clarfication: Read More
So what you want in this to have an abstract class in the background, not an interface. Now how does that look?
Here we have our Kit, every class implementing
Kit
will have access to thename
field. I might recommend putting it in caps if it is supposed to be a constant. It might be best with a static property as well. More of that can be read here.To illustrate I've made two classes inherit from our
abstract class Kit
.Ninja
andTest
.This class purpose is just to check if
name
really has the value ofFoo
or not.Then we need our actual test class as well.
They are both of different types,
Test
resp.Ninja
but they both have the value offoo
in theirname
field. It will be true for every class that inherits fromKit
.If must be overriden is a requirement then I suggest to add a
constructor
ofKit
to force the user to add data from the base class.Now every class that inherits from
Kit
must invokesuper (String)
, meaning thename
field will be set for every object. It can be different fromclass A extends Kit
andclass B extends Kit
. Is that what you searched for?If so, then implementing
class A
andclass B
will look along these lines.And for
B
it will be the following.Now they are different classes, can hold different fields and methods, but they both need to set the
name
field of the base class:Kit
.