Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface variables.

 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All.
I have a performance related question regarding interface variables.
Consider the following interface...
interface I { // First case
int i=0;
}
Since all variables declared in an interface are implicitly 'public static final', is it better to specify this explicitly as in the following?
interface I { // Second case
public static final int i=0;
}
My hunch is that there would be no problem or overheads with the Second case since final variables are compile time constants & do not have any effect during Runtime.
Pls. give your comments on above.
thanks
- Himanshu
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Himanshu Jhamb:
Since all variables declared in an interface are implicitly 'public static final'...

Based upon the fact that any member variables in an interface are implicitly static and final, I would assume that writing your code in either way would result in the same bytecodes being produced.
Indeed, I just compiled the following code:

After using javap to look at the bytecode, I see this was produced:

Corey
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Himanshu,
Performance-wise, it probably makes no difference at all. But explicitly declaring interface variables as public static final is better coding style since even novices (who might not know this implicit rule) can see your intent.

Hope this helps
Michael Morris
SCJP2
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic