Java enum instatiate using constructor parameter Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java enum instatiate using constructor parameter without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have this enum:

    public enum Operation {
        ADD {
            public double apply(double a, double b) {
                return a + b;
            }
        },
        SUBTRACT {
            public double apply(double a, double b) {
                return a - b;
            }
        }
        } ;

        public abstract double apply(double a, double b);
`}`

I want to instantiate this like:

Operation op=new Operation("+");
op.aply(2,3);//now use ADD

Is it possible to write a constructor with string parameter that tells to enum which operation to aply?

Answer

You can define a public static method to get the correct operation based on a String:

public static Operation get(String input) {
    if(input.equals("+")) {
        return ADD;
    }
    if(input.equals("-")) {
        return SUBTRACT;
    }
    throw new IllegalArgumentException();
}

Then you would call it like:

Operation op = Operation.get("+");
op.apply(2, 3);
We are here to answer your question about Java enum instatiate using constructor parameter - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji