How to use constructor in enum? - java

I want to use an enum to create a singleton class in java. Should look like this:
public enum mySingleton implements myInterface {
INSTANCE;
private final myObject myString;
private mySingleton(myObject myString) {
this.myString= myString;
}
}
Looks like I cannot use any parameters in the constructor. Is there any workaround for this? Thanks in advance

Yor enum is wrong. Below correct declaration:
public class Hello {
public enum MyEnum {
ONE("One value"), TWO("Two value"); //Here elements of enum.
private String value;
private MyEnum(String value) {
this.value = value;
System.out.println(this.value);
}
public String getValue() {
return value;
}
}
public static void main(String[] args) {
MyEnum e = MyEnum.ONE;
}
}
Output:
One value
Two value
Conctructor is invoked for each element of enum.

You can try this:
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs "
+ c.getPrice() + " thousand dollars.");
}
}
Also see more demos

Related

How to change the value of private variable in java

I started to programm in Java since Yesterday, and I have the biggest question of my entire programmer life(since Yesterday).
For example, let's say I have a code like this:
public class itsAClass {
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
return A;
}
}
I wanted to use the method something() in another Class to get the String Sentence of A, but I got only null.
How can I change the value of A, so that the another Class can get the Value "This should be changed"?
If you just want to bring this code to work you just can make something() static as well.
But this will be not the right way to approach this problem.
If you want to hold code in the main class you could do something like this:
public class AClass {
private String a;
public static void main() {
AClass myC = new AClass();
myC.setA("This should be changed");
// than use myC for your further access
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
If you want to access it by a external class without direct reference you can checkout the singleton pattern.
public class AClass {
private final static AClass INSTANCE = new AClass();
private String a;
public static void main() {
getSingleton().setA("This should be changed");
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public static AClass getSingleton() {
return INSTANCE;
}
}
This way you can access it via AClass.getSingleton() from any location of your code.
You have to call your main() function.
In another class:
itsAClass aClassObj = new itsAClass();
aClassObj.main();
// or rather itsAClass.main() as it is a static function
// now A's value changed
System.out.println(aClassObj.something());
the way to set the value of private variable is by setter and getter methods in class.
example below
public class Test {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}
you can call method main() in method something().
public class itsAClass{
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
main();
return A;
}
public static void main(String[] args){
itsAClass a1 = new itsAClass();
System.out.println(a1.something());// prints This should be changed
}
}

enum does not provide expected result

I have defined an enum in a class A
public class A{
public static final String CANDY = "yelow candy";
public static final String CAKE = "cookie";
public enum Yummy{
CANDY, CAKE;
}
}
In another package,
public class C {
Yummy[] yummies = A.Yummy.values();
for (Yummy yum : yummies){
String yumString = yum.toString();
System.out.println("yum =" + yumString);
}
}
I get CANDY and CAKE as a result, not "yelow candy" and "cookie".
What does I need to change to get the "yelow candy" and "cookie ?
You've defined an enum "A.Yummy" and also two strings, "A.Candy" and "A.CAKE".
They aren't linked at all.
You will want to delete the strings and add something like https://stackoverflow.com/a/13291109/1041364
public enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String description;
private Yummy(String description) {
this.description= description;
}
public String toString() {
return this.description;
}
}
Try the following:
public enum Yummy{
CANDY ("yellow candy"), CAKE ("cookie");
private String name;
private Yummy(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Additional values for enums should be hold in properties. You have to provide constructor to set up those properties.
public enum Yummy {
CANDY("yelow candy"), CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
};
And then in code you can use CANDY.value or override toString() method.
Try this:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for (Yummy yum : Yummy.values()) {
System.out.printf("%s, %s\n", yum, yum.getValue());
}
}
}
enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}

Using enums in Java

Constants given in the following enum,
enum StringConstatns {
ONE {
#Override
public String toString() {
return "One";
}
},
TWO {
#Override
public String toString() {
return "Two";
}
}
}
public final class Main {
public static void main(String... args) {
System.out.println(StringConstatns.ONE + " : " + StringConstatns.TWO);
}
}
can be accessed just like StringConstatns.ONE and StringConstatns.TWO as shown in the main() method.
I have the following enum representing an int constant(s).
public enum IntegerConstants
{
MAX_PAGE_SIZE(50);
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This requires accessing the constant value like IntegerConstants.MAX_PAGE_SIZE.getValue().
Can this enum be modified somehow in a way that value can be accessed just like IntegerConstants.MAX_PAGE_SIZE as shown in the first case?
The answer is no, you cannot. You have to call:
IntegerConstants.MAX_PAGE_SIZE.getValue()
If you really want a shortcut, you could define a constant somewhere like this:
public class RealConstants {
final public static int MAX_PAGE_SIZE = 50;
}
public enum IntegerConstants
{
MAX_PAGE_SIZE(RealConstants.MAX_PAGE_SIZE);//reuse the constant
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This is not going to work because your first example does implicit calls to .toString() when you concatenate them with +, whereas there is no implicit conversion to int which is needed for your second example.
You could define them as static final fields, this does exactly what you are searching for:
public class IntegerConstants {
public static final int MAX_PAGE_SIZE = 50;
}

enum properties & side effects

I have a question regarding enum (it might be a simple one but ....).
This is my program:
public class Hello {
public enum MyEnum
{
ONE(1), TWO(2);
private int value;
private MyEnum(int value)
{
System.out.println("hello");
this.value = value;
}
public int getValue()
{
return value;
}
}
public static void main(String[] args)
{
MyEnum e = MyEnum.ONE;
}
}
and my question is: Why the output is
hello
hello
and not
hello
?
How the code is "going" twice to the constructor ?
When is the first time and when is the second ?
And why the enum constructor can not be public ?
Is it the reason why it print twice and not one time only ?
Enums are Singletons and they are instanciated upon loading of the class - so the two "hello"s come from instanciating MyEnum.ONE and MyEnum.TWO (just try printing value as well).
This is also the reason why the constuctor must not be public: the Enum guarantees there will ever only be one instance of each value - which it can't if someone else could fiddle with the constructor.
How the code is "going" twice to the constructor ?
Conctructor is invoked for each element of enum. Little change your example for demonstration it:
public class Hello {
public enum MyEnum {
ONE(1), TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
System.out.println("hello "+this.value);
}
public int getValue() {
return value;
}
}
public static void main(String[] args) {
MyEnum e = MyEnum.ONE;
}
}
Output:
hello 1
hello 2
Your constructor invoke twice. The moment of loading your Enum class it will invoke number of time which equals to number of enum types here.
MyEnum e = MyEnum.ONE; // singleton instance of Enum
consider following
public class Hello {
public enum MyEnum
{
ONE(1), TWO(2), THREE(3);
private int value;
private MyEnum(int value)
{
System.out.println("hello"+value);
this.value = value;
}
public int getValue()
{
return value;
}
}
public static void main(String[] args)
{
MyEnum e = MyEnum.ONE;
}
}
Out put
hello1
hello2
hello3

Selecting correct Enum

I have a number of Enums each of which contain the names of attributes to be tested. The problem I have is how to select the relevant enum for the object. How can I define just a Enum variable which use throughout my code which can be set through an initalise method.
EDIT:
Sorry for the delayed reponse. I had to step away from the desk
It very well be bad design. I have a few enums as follows:
public enum AccountGrpEnum {
Account("Account"),
AccountType("AccountType"),
AcctIDSource("AcctIDSource");
private static Set<String> grpNames = new HashSet<String>(3) {{
for(AccountGrpEnum e : AccountGrpEnum.values()) {
add(e.toString());
}
}};
public static boolean contains(String name) {
return grpNames.contains(name);
}
private String name;
private AccountGrpEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Another Enum:
public enum BlockManValEnum {
avgPx("avgPx"),
quantity("quantity"),
securityIDSource("securityIDSource"),
securityID("securityID"),
blockStatus("blockStatus"),
side("side");
private static Set<String> names = new HashSet<String>(9) {{
for(BlockManValEnum e : BlockManValEnum.values()) {
add(e.toString());
}
}};
public static boolean contains(String name) {
return names.contains(name);
}
private String name;
private BlockManValEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Within my code I am checking the fields of an incoming object to see they are contained within the Enum. As follows:
if (BlockManValEnum.contains(fields[i].getName()))
however I would like it to be along the lines of
if (variableEnum.contains(fields[i].getName()))
Where variableEnum can be set at runtime.
Hope this is clearer guys
Building on previous answers.
enum Color {
RED(1),
GREEN(2),
BLUE(3);
int attrib;
Color(int attribValue) {
attrib = attribValue;
}
public Color getColorForAttrib(int attribValue) {
for(Color c : Color.values()) {
if(c.attrib == attribValue) {
return c;
}
}
throw new IllegalArgumentException("No color could be found for attrib of value " + attribValue);
}
}
...
class SomeClass {
Color c;
public void SomeClass(Color c) {
this.c = c;
}
}
...
class SomeClassUser {
public static void main(String[] args) {
Color c = Color.getColorForAttrib(Integer.valueOf(args[i]));
new SomeClass(c);
}
}
Remember that simplistically, enums are just a class, so you can add any methods you want to them. Whether or not it's a good idea depends on circumstance
Use Enum.valueOf:
Enum<?> variableEnum = AccountGrpEnum.class;
if(Enum.valueOf(variableEnum.getClass(), field[i].getName()) != null) {
doSomething();
}
Since enums are classes and thus can implement interfaces, you could create an interface which holds your contains() method and then implement that method on your enums, then use a generic method which takes a class token of a specific enum type implementing that interface (and which could be set at runtime) to test. Something like this:
CanBeTestedForContains:
public interface CanBeTestedForContains {
boolean contains(String name);
}
ColorEnum:
import java.util.HashSet;
import java.util.Set;
public enum ColorEnum implements CanBeTestedForContains {
R("red"),
B("blue");
private static Set<String> names = new HashSet<String>(3) {
{
for (final ColorEnum e : ColorEnum.values()) {
add(e.name);
}
}
};
private String name;
private ColorEnum(final String name) {
this.name = name;
}
#Override
public boolean contains(final String name) {
return names.contains(name);
}
}
SuitEnum:
import java.util.HashSet;
import java.util.Set;
public enum SuitEnum implements CanBeTestedForContains {
D("diamonds"),
H("hearts"),
C("clubs"),
S("spades");
private static Set<String> names = new HashSet<String>(3) {
{
for (final SuitEnum e : SuitEnum.values()) {
add(e.name);
}
}
};
private String name;
private SuitEnum(final String name) {
this.name = name;
}
#Override
public boolean contains(final String name) {
return names.contains(name);
}
}
ContainsSelectorTest:
public class ContainsSelectorTest {
private static <E extends Enum<E> & CanBeTestedForContains> boolean contains(final Class<E> enumClass, final String name) {
return enumClass.getEnumConstants()[0].contains(name);
}
public static void main(final String[] args) {
if (contains(ColorEnum.class, "red")) {
System.out.printf("%s contains %s\n", ColorEnum.class, "red");
}
if (contains(SuitEnum.class, "hearts")) {
System.out.printf("%s contains %s\n", SuitEnum.class, "hearts");
}
if (contains(SuitEnum.class, "red")) {
System.out.println("This shouldn't happen.");
} else {
System.out.printf("%s DOES NOT contain %s\n", SuitEnum.class, "red");
}
}
}
Output:
class ColorEnum contains red
class SuitEnum contains hearts class
class SuitEnum DOES NOT contain red

Categories

Resources