Re: Declaring members for Interfaces
On Tue, 22 Apr 2008 22:54:28 -0700 (PDT) vamsee.maha@gmail.com wrote:
Can anyone tell me reason:
Why the syntax for declaring members in interfaces are declared as
constants.
Well the usual idea is that you dont need to qualify your constants if you
put them into an interface. Assume this:
class MyConstants {
public static String MY_STRING = "foo";
}
Now if you want to use this in a class of yours:
class MyWindow extends JFrame {
private void buildUI() {
...
field.setText(MyConstants.MY_STRING);
....
}
}
If you declare the constants in an interface:
interface MyConstants {
public static String MY_STRING = "foo";
}
you can do
class MyWindow extends JFrame implements MyConstants {
private void buildUI() {
...
field.setText(MY_STRING);
....
}
}
since you inherited the constants from the interface. Note however, that
this is considered bad style by many people, as you can get into trouble
when you have the same constant name in different interfaces. Also you are
misusing the idea of interfaces for saving some typing, which can be
considered a hack. The preferred way of doing this in Java 1.5 or above is
using static imports:
import static MyConstants.*;
class MyWindow extends JFrame {
private void buildUI() {
...
field.setText(MY_STRING);
....
}
}
Jan