How to use enum that are not int type in the switch( ) statement in java?

B

Bruce Sam

/* ******************************* */
class PDomainEnum {
public static final int PDPoint = 0;
public static final int PDLine = 1;
}

class PDomain {
PDomainEnum type;

public void within(type) {
switch(type) {
case PDPoint:
break;
case PDLine:
break;
default:
break;
}
}
}
/* ************************** */
The above is a not a completed program but just to show
something.I want to create an enum PDomainEnum,it has two variable
PDPoint and PDLine.In PDomain,I define an object of PDomainEnum
type.The most important thing that I want to do is use the switch( ) to
select statement.I know switch not allow the non-int type in it.But I
can't find a method to implement the selection statement.Could you give
me some advice?Addtional,I'm using J2SE 1.4.2,and has some reason I
can't not use J2SE1.5.
 
A

Andrew McDonagh

Bruce said:
/* ******************************* */
class PDomainEnum {
public static final int PDPoint = 0;
public static final int PDLine = 1;
}

class PDomain {
PDomainEnum type;

public void within(type) {
switch(type) {
case PDPoint:
break;
case PDLine:
break;
default:
break;
}
}
}
/* ************************** */
The above is a not a completed program but just to show
something.I want to create an enum PDomainEnum,it has two variable
PDPoint and PDLine.In PDomain,I define an object of PDomainEnum
type.

This is the problem, you should be defining an int, see below.

The most important thing that I want to do is use the switch( ) to
select statement.I know switch not allow the non-int type in it.But I
can't find a method to implement the selection statement.Could you give
me some advice?Addtional,I'm using J2SE 1.4.2,and has some reason I
can't not use J2SE1.5.

Your problem is that the 'within' method takes an instance of
PDomainEnum Class. Yet the PDomainEnum class is not your enum, but just
the class where the enums PDPoint & PDLine are defined.

so, change the signature of the 'within()' method to accept an 'int' and
call it like this.

PDomain p = new PDomain()

p.within(PDomainEnum.PDLine);



Having said all of this, your 'enums' are just static int's. Which is
fine, but very crude. Have a google for the Type-Safe enum idiom.

Also, google for 'refactoring replace conditional'.

One of the first links should be...

http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top