Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Ella Campbell   on Dec 05 In Java Category.

  
Question Answered By: Percy Morgan   on Dec 05

I think that the main reason is laziness. Personally I prefer a system similar
to what you describe. Here is an example:

public final class  ConsoleType{

public static  final int  GUI_TYPE = 1;
public static final int CONSOLE_TYPE = 2;

public static final ConsoleType GUI = new ConsoleType(GUI_TYPE);
public static final ConsoleType CONSOLE = new ConsoleType(CONSOLE);

private static final HashMap typeToStringMap = new HashMap();
static{
typeToStringMap.put(GUI, "GUI");
typeToStringMap.put(CONSOLE, "Console");
}

private int value = -1;

private ConsoleType(int value){
this.value = value;
}

public int getValue(){
return value;
}

public String toString(){
return (String)typeToStringMap.get(this);
}

}


The nice thing about this "type" class is that:

a.) you can not create  unknown types because you cannot directly instantiate
the class
b.) you still have access to an int value and constant representations so you
can do switch statements:

switch(type.getValue()){
case ConsoleType.GUI_TYPE:
// do something
break;
case ConsoleType.CONSOLE_TYPE:
// do something else
break;
default:
throw new IllegalArgumentException("Invalid type: " + type);
}


But as you can see creating these types of classes  does take more effort than
just passing an int.

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 


Tagged: