0

I am trying to do a bit of reverse engineering on enum.

public class test {
    public static void main(String[] args) {
        num number=num.one;
        System.out.println(number); //outputs result as one

    }
}

enum num{
    one;
}

Now how do I implement the same without using enum.

public class Lab24a {
    public static void main(String[] args) {
        num1 num= num1.one;
        System.out.println(num);
    }
}

class num1{
    public static final num1 one= new num1();

    private num1(){
    }

    public String toString(){
        return //how to implement the two string totally lost here.
    }
}

I was able to write a code until this, but I am not able to printout the value, please give me your suggestions or hints. I even tried looking at the following links.

Confusion with Enum type

enum implementation inside interface - Java

Community
  • 1
  • 1
User27854
  • 824
  • 1
  • 16
  • 40

1 Answers1

3

Why not use an enum? IMO Java is missing some key features, but one of the things it does right it is the way it uses enums.

If you really want to avoid an enum, you could do this:

class num1{
    public static final num1 one= new num1("one");

    private String name;
    private num1(String name) {
        this.name = name;
    }

    @Override  //Be sure to add the override annotation here!
    public String toString(){
        return name;
    }   
}
musical_coder
  • 3,886
  • 3
  • 15
  • 18
  • I am not passing anything in my constructor, its a default one. – User27854 Mar 23 '14 at 05:47
  • I understand the benefits, I just wanted to understand things in much depth, so trying to learn. I even tried reading the generated class file, but it showed nothing, just enum and the code. – User27854 Mar 23 '14 at 05:48
  • This is your code, so you're free to change the constructor, right? I don't see a better way to solve your problem than the solution I posted. The bottom line with Java enums is that each member (such as `one` in your example) is a full-blown object on its own. – musical_coder Mar 23 '14 at 05:52
  • here even we have created an object right. using the new keyword, and I was trying to mimic it. – User27854 Mar 23 '14 at 05:55