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
Kitto 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
Kitwill have access to thenamefield. 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.NinjaandTest.This class purpose is just to check if
namereally has the value ofFooor not.Then we need our actual test class as well.
They are both of different types,
Testresp.Ninjabut they both have the value offooin theirnamefield. It will be true for every class that inherits fromKit.If must be overriden is a requirement then I suggest to add a
constructorofKitto force the user to add data from the base class.Now every class that inherits from
Kitmust invokesuper (String), meaning thenamefield will be set for every object. It can be different fromclass A extends Kitandclass B extends Kit. Is that what you searched for?If so, then implementing
class Aandclass Bwill look along these lines.And for
Bit will be the following.Now they are different classes, can hold different fields and methods, but they both need to set the
namefield of the base class:Kit.