Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface

 
Shivkant Pandey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am new to this community. I have few questions in my mind taking Interface

1) Interface can have variables and internally makes it public static and final. If we talk design wise where exactly we may need these variables?

And also in case an interface I1 extends another interface I2 then if I2 has a variable
public static final int testValI2=12;
so design wise this variable is accessible to I1. When we will be this kind of situation? Inheritance is the property of classes not of Interface so what does it exactly means when an interface is exteding another interface?

2) if Class A implements Interface I1 and interace has a variable which by default will be static? So when this variable be loaded as this is static?

Thanks
Shivkant
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you are calling interface variables are really just constants (static final). You generally use constants for things like, for example, Strings that you don't want to hard-code into the code. You extend an interface for the same reason you extend a class. The base interface has functions (or constants) that a set of interfaces have in common. Static final variables are initialized when the class that implements the interface is loaded for the first time.
 
Yogesh Gnanapraksam
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having an interface for constants is considered to be anti-pattern.

Constant-Interface-Antipattern

Thanks
yogi
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm - both of the responses above are generally true, but not always. Since I've written about both issues in the past, I'll just link to past posts:

Interface variables aren't always constants

Constant interfaces aren't always an antipattern.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic