Java Interface Variable members

Introduction

We can use interfaces to import shared constants into multiple classes.


import java.util.Random;

interface SharedConstants {
  int NO = 0;//from  ww w  . ja va2 s .  co  m
  int YES = 1;
  int OTHER = 3;
}

class Question implements SharedConstants {
  Random rand = new Random();
  int ask() {
    int prob = (int) (100 * rand.nextDouble());
    if (prob % 2 == 0)
      return NO;  
    else if (prob % 5 == 0)
      return YES;     

    return OTHER;        
  }
}

public class Main implements SharedConstants {
  static void answer(int result) {
    switch(result) {
      case NO:
        System.out.println("No");
        break;
      case YES:
        System.out.println("Yes");
        break;
    }
  }

  public static void main(String args[]) {
    Question q = new Question();
    answer(q.ask());
    answer(q.ask());
    answer(q.ask());
    answer(q.ask());
  }
}



PreviousNext

Related