Java-Enumeration Class Types(Another Example)

Enumeration Class Types

In the following program, the version of Fruits adds three things. The first is the instance variable rate, which is used to hold the rate of each variety of fruits. The second is the Fruits constructor, which is passed the rate of an fruit. The third is the method getRate( ), which returns the value of rate.

When accessing any Fruits constant in main( ), the constructor for Fruits is called once for each constant that is specified. Notice how the arguments to the constructor are specified, by putting them inside parentheses after each constant. The values are passed to the ‘ra’¬†parameter of Fruits( ), which then assigns these value to rate. Again, the constructor is called once for each constant. Because each enumeration constant has its own copy of rate, you can obtain the rate of a specified type of fruit by calling gerRate( ).

Program

0

Program Source

enum Fruits {
    
    Apple(10), Banana(20), Cherry(30), Date(40), Elderberry(50);

    int rate;
       
    Fruits(int ra)
    {
        rate = ra;
    }
    
    int getRate()
    {
        return rate;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        System.out.println("Apple      : "+Fruits.Apple.getRate());
        System.out.println("Cherry     : "+Fruits.Cherry.getRate());
        System.out.println("Elderberry : "+Fruits.Elderberry.getRate());
    }
}

Leave a Comment