Hello my problem here i'm trying to retrive the valu which is assigned in the interface.But i'm getting compilation errors.Cud u pls help me in this regd to retrive value from interface [ August 30, 2004: Message edited by: Barry Gaunt ]
An interface is supposed to supply the conditions of a contract that the class needs to meet, not supply constants. There is also the consideration of scope of i; if MyClass.i is renamed, then the i in the interface can be accessed without using the MyIntr prefix.
Hope that helps,
The nice thing about Standards is that there are so many to choose from!
Joined: Aug 03, 2002
Thank you Eddie, typo fixed. Actually it compiles with MyClass.i too
Regarding the interface providing constants: it's commonly done, see for instance PathIterator.WIND_EVEN_ODD, PathIterator.WIND_NON_ZERO... in the java.awt.geom package. You define constants in an interface because you can implement more than one such interface. If you define your constants in a class you are stuck with inheriting from that class and only that class.
[ August 30, 2004: Message edited by: Barry Gaunt ] [ August 30, 2004: Message edited by: Barry Gaunt ]
Joined: Mar 18, 2003
I too have used constants defined in interfaces, but I have learnt from experience that you'd better have a good global file text find function when you need to find which interface the constant is in. I now prefer to put my constants as static variables in appropriate classes so I refer to each one by class.name - gives me more info about where it's defined and how it's used.
First, in the main method of your code, you declare an interface called intr -- but that reference is never assigned to anything. (Have you created any objects here? Any use of the keyword "new"?)
Second, you did implement your interface in MyClass. However, you never actually created an instance of MyClass.
Third, variables in interfaces are essentially constants. They are implicitly public, static, and final. So when you do create an instance of MyClass, it will have a final i = 10 (the value you assigned in the interface). BUT...
Fourth, in main, when you define int i = 20; you've declared a local variable, valid only within the scope of the main method. It's important to realize that this is not the same int i that's in MyClass. So when you display "value of i is " + i, you're only referencing the local variable -- not at all touching the int i in MyClass.
Fifth, you can't instantiate an interface, but you can upcast an object that implements the interface.
I hope this helps...
[ September 01, 2004: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org