Skip to content
Related Articles

Related Articles

How to Use Enum, Constructor, Instance Variable & Method in Java?
  • Last Updated : 02 Feb, 2021

Enumerations serve the purpose of representing a group of named constants in a programming language.

Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java, enums are represented using enum data type. Java enums are more powerful than C/C++ enums . In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).

Instance variables are non-static variables and are declared in a class outside any method, constructor, or block.

Problem description :

Our problem is how to use enum Constructor, Instance Variable & Method in Java.



So, for this solution, we will see the below example initializes enum using a constructor & totalPrice() method & display values of enums.

Code:

Java




// Java program to show the use of
// enum Constructor, Instance Variable & Method
  
import java.io.*;
import java.util.*;
  
enum fruits 
{
    Apple(120),
    Kiwi(60),
    Banana(20),
    Orange(80);
     
    // internal data
    private int price;
    
    // Constructor
    fruits(int pr) 
    
      price = pr; 
    }
    
    // method
    int totalPrice() 
    
      return price; 
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        System.out.println("Total price of fruits : ");
        
        // range based for loop
        for (fruits f : fruits.values())+ f.totalPrice()
                               + " rupees per kg.");
    }
}
Output
Total price of fruits : 
Apple costs 120 rupees per kg.
Kiwi costs 60 rupees per kg.
Banana costs 20 rupees per kg.
Orange costs 80 rupees per kg.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :