• Post Reply Bookmark Topic Watch Topic
  • New Topic

JavaDocs says interfaces cannot have fields.Why?  RSS feed

 
Prashant Soood
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the link http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html and it says One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot.How can this be possible?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about it - to have a field you have to have an object.
 
Prashant Soood
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But I can write public static final String abc="Hello"; in an interface
 
Dieter Quickfend
Bartender
Posts: 543
4
Java Netbeans IDE Redhat
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashant Soood wrote:But I can write public static final String abc="Hello"; in an interface

True enough. I guess 'field' is kind of ambiguous. What the writer means to say is interfaces cannot have variables. The only fields allowed in an interface are constant (final) fields. Some would classify "field" as a variable, some would also call constants "fields". It's a matter of interpretation.

Mind: interface constants are NOT inherently immutable. So while you cannot reassign final references, you can reassign the properties (if any) of the object a final reference is pointing to, unless that object is immutable.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"public static final" is really constants which interfaces are indeed allow.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashant Soood wrote:But I can write public static final String abc="Hello"; in an interface


And the object it exists in is the java.lang.Class object - which is not an instance of the Interface.

Bill
 
krishna atok
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interface is a specification with out any implementation. More over it's a contract which enforces all the classes which implements it.
Any implementation can change the values of the fields if they are not declared final.
If they are static then they will belong to interface, but not to the object, nor the run time of the object.
Public, to make these fields enabled to implementation classes.

Enums are being widely used to represent any meaningful constants
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!