The interface point is to specify the public API. The interface has no state. Any variables that you create are really constants (so be careful when creating mutable objects in interfaces).
Basically, the interface says that these are all methods that the class that implements it must support. It would probably be better if the creators of Java did not allow constants in interfaces, but too late to get rid of it now (and there are some cases where constants are reasonable in interfaces).
Since you simply indicate which methods should be implemented, there is no concept of state (no instance variables). If you want each class to have a specific variable, you need to use an abstract class.
Finally, you should generally not use public variables, so the idea of entering variables into an interface is a bad idea to start with.
The short answer is that you cannot do what you want, because it is "wrong" in Java.
Edit:
class Tile implements Rectangle { private int height; private int width; @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public void setHeight(int h) { height = h; } @Override public void setWidth(int w) { width = w; } }
an alternative version would be:
abstract class AbstractRectangle implements Rectangle { private int height; private int width; @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public void setHeight(int h) { height = h; } @Override public void setWidth(int w) { width = w; } } class Tile extends AbstractRectangle { }
TofuBeer Sep 05 '11 at 18:02 2011-09-05 18:02
source share