Re: Simple question about Java Methods
Danger_Duck wrote:
Doh!, I guess enumerations in Java aren't as bad as I thought, in
addition to not being able to interchange them with integers, I was
always turned off by the below link, but turns out that I misread it:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
That there is some pretty complex use of enums.
All you really need is:
enum Waves { sine, square, sawtooth }
Then you can do things like specify them as parameters to your method
public void method1( Waves w ) {
switch (w) {
case sine:
// Draw a sine wave
case square:
// Draw a square wave
case sawtooth:
// Draw a sawtooth wave
}
}
This is pretty unsophisticated use of enums, but it works. If you don't
like the examples up-thread (which are better, btw) then this will work
just fine until you get used to doing more tricky things with enums.
I had thought that a client program had to instantiate an instance of
the enumeration, then call a method on it. Now I realize that I
thought the class "EnumTest" was the enumeration :)
Nope, you don't have to do that if you don't want to. You can, and it
can often be better to do so, but if you don't understand it then I
would just concentrate on writing code you understand and can maintain
and worry about the tricky stuff later.
While I still don't like how Java does not provide direct access to
the enumeration like in C, your way works fine for what I want here,
and it looks like I was too quick to bash what I had in fact misread.
What kind of direct access are you looking for? It's easy to concert
enums into integers: sine.ordinal() will convert "sine" into a number. I
don't see immediately how to go in the other direction, but I think
Waves.values() will always return an array in ordinal order.