Here we have created just simple text based game in java using interface.Its just one type of puzzle that can help you understand interface.If you still don’t know about interface then click here to get detailed guide about interface

  • Please note that the output will  be different at every time execution of below code because we randomly gets the number using java file

Also read:- Ternary operator in java

Source code

import java.util.Random;
interface variables     //interface
{
int no=0;
int yes=1;
int maybe=2;
int later=3;
int soon=4;
int never=5;
}
class question implements variables        //class implements interface
{
Random rd=new Random();
int temp=(int) (100*rd.nextDouble());
int ask(){
if(temp<30)
{
return no;
}
else if(temp<60)
{
return yes;
}
else if(temp<75)
{
return maybe;
}
else if(temp<98)
{
return soon;
}
else
return never;
}
}
class ask implements variables  //class implements interface
{
static void answer(int cal)
{
switch(cal)
{
case no:
 System.out.println(“No”);
 break;
 case yes:
 System.out.println(“yes”);
 break;
 case maybe:
 System.out.println(“maybe”);
 break;
 case soon:
 System.out.println(“soon”);
 break;
 case never:
 System.out.println(“never”);
 break;
 }
 }
 }
 class game       //main class
{
 public static void main(String args[])
 {
 question q=new question();      //first class object
ask.answer(q.ask());
ask.answer(q.ask());           
ask.answer(q.ask());                           //calling all functions
ask.answer(q.ask());


}
}

output

never
never
never
never

Logic 

 Here first we have select one file named random,then created one interface.This interface has six integer variables and having different value.

Also read:-Java basic structure with first program

Now there is one class that name is question,which implements the above interface.Now we have created the object of random file and used it to get integer values.The value which was generated by object could be stored inside temp variable.Now there is one function which have int return type and use some condition as per interface variables.Now we have second class that is ask .That class also implements interface and perform different operations using first class value as you can see in program.In second class we have used switch statement.Now in the main class we have created object of question class and used it to call the function.Here you may have confusion but you will get exact idea if you execute it into your system.Your output can be different because of random file.so don.t worry.
If still have query then ask us in comment box don’t forget to like our fb page

By jigar

Leave a Reply

Your email address will not be published. Required fields are marked *