Thursday, 4 June 2015

Java accessing Interface Variables

The variables defined in an interface are implicitly public, static and final as discussed earlier.

The variables can be accessed just like static variables by using name of the interface and dot operator. The following example demonstrates this.

Example:

interface Constants

{

double PI = 3.1415;

double E = 2.712;

float INT_RATE = 10.0f;

}

These constants can be referred from other classes as follows:

Constants.PI, Constants.E, Constants.INT_RATE

The constants defined in the interface Constants can be accessed simply by using their names as PI, E and INT_RATE in the class, which implements the interface Constants.

You can use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables, which are initialized to the desired values.

When you include that interface in a class (i.e., when you “implement the interface”), all of these variables name will be in scope as constants. This is similar to using header file in C/C++ to create a large number of #defined constants or const declarations.

If an interface contains no methods, then any class that includes such an interface does not actually implement anything. It is as if that class was importing the constant variables into the class name space as final variables.

Example:

interface SharedConstants

{

int NO = 0;

int YES = 1;

int MAYBE = 2;

int LATER = 3;

int SOON = 4;

int NEVER = 5;

}

class ConstantsDemo implements SharedConstants

{

public static void main(String args[])

{

System.out.println(NO);

System.out.println(YES);

System.out.println(MAYBE);

System.out.println(LATER);

System.out.println(SOON);

System.out.println(NEVER);

}

}

class ConstantsDemo1

{

public static void main(String args[])

{

System.out.println(SharedConstants.NO);

System.out.println(SharedConstants.YES);

System.out.println(SharedConstants.MAYBE);

System.out.println(SharedConstants.LATER);

System.out.println(SharedConstants.SOON);

System.out.println(SharedConstants.NEVER);

}

}

Output: Output of executing both classes will be same as shown below:

0
1
2
3
4
5

Note: Class “ConstantsDemo” can use the constants defines in the interface  “SharedConstants” without qualifying with the interface name as it implements the interface “SharedConstants”. But class “ConstantsDemo1” can use the constants defined in the interface “SharedConstants” only after qualifying with the interface name, as it does not implement the interface “SharedConstants”.

No comments:

Post a Comment