Skip to content
Advertisement

Attributes / member variables in interfaces?

I wish to know is there any way in which I can make it compulsory for the implementer class to declare the objects handles/primitives as they do with methods. for e.g.:

JavaScript

In the above method how can we compel Tile class to declare height and width attributes using the interface? For some reason I wish to do it with interface only!

I initially thought of using it with inheritance. But thing is I have to deal with 3 classes.!

  1. Rectangle
  2. Tile
  3. JLabel.!

 

JavaScript

would work.!

but

JavaScript

woud not.!

Advertisement

Answer

The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces).

Basically an interface says here are all of the methods that a class that implements it must support. It probably would have been better if the creators of Java had not allowed constants in interfaces, but too late to get rid of that now (and there are some cases where constants are sensible in interfaces).

Because you are just specifying what methods have to be implemented there is no idea of state (no instance variables). If you want to require that every class has a certain variable you need to use an abstract class.

Finally, you should, generally speaking, not use public variables, so the idea of putting variables into an interface is a bad idea to begin with.

Short answer – you can’t do what you want because it is “wrong” in Java.

Edit:

JavaScript

an alternative version would be:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement