Variables in Interfaces
You could use interfaces to import shared constants into multiple classes through simply declaring an interface which holds variables that are initialized to the desired values. When you involve that interface in a class (that is, when you "implement",) all of these variable names will be in scope as constants. This is same to using a header file in C/C + + to create a huge number of # defined constants or const declaration. Any class that involves such an interface doesn't actually implement anything if an interface contains no methods. It is as if that class was importing the constant variables into the class name space as final, variables. The further example uses this method to implement an automated "decision maker".
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER =3;
int SOON =4;
int NEVER =5 ;
}
class Question implements SharedConstants {
Random rand = new Random ( );
int ask ( ) {
int prob =(int ) (100 * rand. nextDouble( ) );
if (prob < 30 )
return NO; / /30%
else if (prob < 60 )
return YES; / / 30%
else if (prob <75)
return LATER / / 15%
else if (prob <98)
return SOON / / 13%
else
return NEVER / / 2%
}
}
class AskMe implements sharedConstants {
static void answer (int result ) {
switch (result ) {
case NO:
System.out.println ("No");
break;
case YES:
System.out.println ("yes");
break;
case MAYBE:
System.out.println ("Maybe");
break;
case LATER:
System.out.println ("later");
break;
case SOON: System.out.println ("soon"); break;
case NEVER: Syste.out.println ("Nnever");
break;
}
}
public static void main (String args [ ] ) Question q= new Question ( );
answer (q.ask ( ));
answer (q.ask ( ) ); answer ( q.ask( ) ); answer ( q.ask ( ) ) ;
}
}
Note that this program makes use of one of Java's standard classes: Random. This class gives pseudorandom numbers. Which holds various functions that permits you to gain random numbers in the form needed through your program. Within this instance, the method nextDouble ( ) is used. It returns random numbers in the range 0.0 for 1.0
In this given program, the two classes, AskMe and Question, both implement the Shared Constants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined. Within each class, the code refers to these constants as if every class had defined or inherited them directly. Here is the output of a sample run of this program. Remember in which the result are different every time it is run.
Later
Soon
No
Yes