Monday, March 27, 2006

Classes, classes and classes

I'm talking about Java - its a "classy" language. Notice the double quotes - so I define the word classy - its all about classes and classes. Everything has to be a class. There is no concept of globals, enums, structs and all those other fancy stuff that C++ supported to have backward comaptibility with C code. Imagine if you had to define some enum for color. In C++ I would just do the following:

enum colors { RED, BLUE, GREEN, WHITE, BLACK };

Somewhere in my code I could use RED, BLUE, GREEN for equlaity checks or case statement checks.

How do I do the same in Java? I have to create a class and make all these as static constants

public class Constants
{
public static final RED = 1;
public static final BLUE = 2;
...
...
}

Use it in the code as Constants.RED, Constants.BLUE, ...

Ain't it a charm? It depends on how you look at it. With enums life becomes easy to program as you dont have to go through all the roller coaster ride of defining a class structure and making it static. Hence the compiler can be a bit relaxed in these situations BUT there are bigger problems with enums which I will explain in another blog some other day.

One thing about Java - it's a more disciplined language and it forces the programmer to maintain the discipline as there is no alternative way of doing it. No wonder new comers to the OOP world find it easier to learn Java than C++ and old-timers in C++ sit and try to come up with wierd topics for their blogs.

0 Comments:

Post a Comment

<< Home