2

Why does java make a interface data member public & static implicitly?

  • 3
    By "data member" you mean "field", right? – Jon Skeet Feb 25 '14 at 18:27
  • @JeroenVannevel You can just paste the link why you have posted the explanation in the comment ? – Nambi Feb 25 '14 at 18:31
  • What kind of answer are you looking for? Because the only official answer is *"the JLS says so"*. The JLS doesn't provide reasons for their design, only the design itself. – Radiodef Feb 25 '14 at 18:32
  • 3
    @NambiNarayanan: links are context. I make sure that the things I post have a self contained value, as everyone should. – Jeroen Vannevel Feb 25 '14 at 18:33
  • `Interface` variables are `static` because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. – Kick Feb 25 '14 at 18:33
  • This is confusing. If an `interface` is declared inside another class, it is implicitly static, but it doesn't have to be public. Methods declared in the interface are implicitly public and abstract, but not static. I don't know what an "`interface` variable" is, but if you declare a variable whose type is an interface type, it can be public or not, or static or not. – ajb Feb 25 '14 at 18:42
  • 1
    @JeroenVannevel I don't see how your reference to 9.2 is relevant. This is only talking about methods that an interface implicitly inherits from the `Object` class, i.e. `toString()`, `equals()`, etc. – ajb Feb 25 '14 at 18:43
  • Now that I look at it again, I think the question is about constants. – ajb Feb 25 '14 at 18:46
  • @ajb: ah, I totally read past the 'in Object' part. It isn't applicable here indeed; removing it. – Jeroen Vannevel Feb 25 '14 at 19:05

2 Answers2

1

Interfaces only describe external behavior, or "how others see objects of the class implementing this interface" - from this point of view it's rather useless to define something so inherently coupled to internal behaviour as a field. If one wants to prescribe internal behaviour, abstract classes are clearly the way to go.

Smutje
  • 17,733
  • 4
  • 24
  • 41
0

To expand on Smutje's answer a bit: interfaces aren't allowed to define their own data. Because of that, I suspect, the language designers felt that the only legitimate use of data definitions was to define a constant that might be usable by clients; thus, the Action interface in javax.swing has a method

void putValue(String key, Object value)

and the interface also defines some constants that can be used for the key:

public static final String ACTION_COMMAND_KEY = "ActionCommandKey";
public static final String ACCELERATOR_KEY = "AcceleratorKey";

etc. Of course, since those are constants, they aren't data that would be stored in each object that implements the interface. But those are the only kinds of data fields allowed in interfaces.

ajb
  • 31,309
  • 3
  • 58
  • 84