Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question On Interface

 
Marianne Rivera
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am reading head first java book, and I see this statement on page 229

"An interface is like a 100% pure abstract class. It defines only abstract methods."

so I was thinking that if I define an instance variable, the compiler will tell me that there is an error.



but the compiler has no error. Does this mean that if I implement this interface, I automatically inherit also
the intSample?

I was just trying to expirement but I really dont know as of the moment if there is some benefit of doing this.
 
Maneesh Godbole
Saloon Keeper
Posts: 11070
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marianne Rivera wrote: Does this mean that if I implement this interface, I automatically inherit also
the intSample?



Yes you are correct.
Remember, interfaces are not always used as "templates". If you want to define some constants, usually, interfaces are the way to go. Check out SwingConstants for example. It is an interface, and defines many constants used in the swing UI.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Compile it and open in the decompiler
 
Rob Spoor
Sheriff
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seetharaman is right.

Every method declared in an interface is automatically public and abstract, and every field declared is automatically public, static and final.

Maneesh Godbole wrote:If you want to define some constants, usually, interfaces are the way to go.

Ugh, please no.

Joshua Bloch explains why constants interfaces are wrong in Item 19 of his Effective Java book (Item 17 in the first edition). If you want a single place for all your constants, a final utility class should be used. Basically exactly what is described in the book, but the class should also be final (you can't subclass it because the constructor is private; making the class final makes sense).

Sun have used this technique themselves as well, with java.sql.Types (although again, only implicitly final...)
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the information Rob
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
+1 on not using interfaces to define constants, and the Bloch reference explains why.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic