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

1
  • When i am trying to use num again, i am getting error. Commented Mar 23, 2014 at 5:36

1 Answer 1

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;
    }   
}
Sign up to request clarification or add additional context in comments.

4 Comments

I am not passing anything in my constructor, its a default one.
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.
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.
here even we have created an object right. using the new keyword, and I was trying to mimic it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.