Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating an enum

Tags:

java

enums

The below code throws a lot of errors at me. So why is it not possible to have an enum like below with only the constructor so that it can be instantiated else where??

public  class TestEnum{
     enum Animal
     {
         public Animal(String name)
         {
             this.name = name;
         }
         String name;
     }
}

Is there any way of instatiating enum or does it violate the very basic property/functionality of enums and it should only be used for creating a set of,say, ready-made objects??

like image 449
Aarish Ramesh Avatar asked Jan 11 '23 16:01

Aarish Ramesh


1 Answers

Because an enum consists of enumerated constant values (that is constant at compile and run-time)

Your code is otherwise (almost) correct, for example

enum Animal {
  Dog("Bark"), Cat("Meow"); // Dog and Cat.
  Animal(String name) {     // No, it can't be public.
    this.name = name;
  }

  String name;
}

If you want dynamic values, use a class.

like image 196
Elliott Frisch Avatar answered Jan 22 '23 05:01

Elliott Frisch