Home > OS >  How to create an object while using enum in a class?
How to create an object while using enum in a class?

Time:10-19

I previously have the variable availability stored in a double which is present inside a class named wrapper as below -

public final class Wrapper {

private final double availability;


Wrapper(){
this.availability = 2;
}


public Wrapper(final double availability){
this.availability = availability;
}

public double availability (){  // Need a confirmation if this is a getter ?
return this.availability;
}
}

Now, I have to change the scenario a bit by making availability as an object.Reason being - Now we want availability per region unlike the above case.Also, we need to use that availability object inside the wrapper class now.

Here is what I'm trying to do -

public final class Availability {
public enum Region {
US,
UK,
EU;

private final double availability;

Region () {
this.availability = 2;
}

Region (double availability) {
this.availability = availability ;
}
}

I'm supposed to use the Availability object inside wrapper class as wrapper class object is being used in other places which previously used to take argument (Availability). Now I don't want to break that workflow. Also I'm a bit confused a bit regarding creation of object for Availability class as I'm using an enum. Can anyone please help me with this. Thanks in advance!

@override
public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null || getClass() != other.getClass()) {
            return false;
        }
        return this.availability == ((Wrapper) other).availability;
    }  

Do we have to use this in wrapper class itself / how can we use it in enum ?

CodePudding user response:

Per my understanding, you do not need class Availability.

Define Region.java file as having public enum Region, then you can have that constructor along with adding a missing getter.

public enum Region {
    US(2),
    UK(2),
    EU(2);

    private final double availability;

    Region (double availability) {
        this.availability = availability ;
    }

    public getAvailability() {
        return this.availability;
    }
}

Then Wrapper can accept Region instance instead, and access .getAvailability() method of it.

public final class Wrapper {

    private final Region region;
    
    public Wrapper(Region region){
        this.region = region;
    }
    
    public double getAvailability() {
        return this.region.getAvailability();
    }

e.g. System.out.print(new Wrapper(Region.US).getAvailability());

  • Related