Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaHow to Use Enum, Constructor, Instance Variable & Method in Java?

How to Use Enum, Constructor, Instance Variable & Method in Java?

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).

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

Now coming to our problem description as it is to illustrate 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 & displays values of enums.

Example

Java




// Java program to Illustrate Usage of Enum
// Constructor, Instance Variable & Method
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Enum
enum fruits {
    // Attributes associated to enum
    Apple(120),
    Kiwi(60),
    Banana(20),
    Orange(80);
 
    // internal data
    private int price;
 
    // Constructor
    fruits(int pr) { price = pr; }
 
    // Method
    int totalPrice() { return price; }
}
 
// Main class
class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
        // Print statement
        System.out.println("Total price of fruits : ");
 
        // Iterating using enhanced for each loop
        for (fruits f : fruits.values())
 
            // Print anddispaly the cost and perkg cost of
            // fruits
            System.out.println(f + " costs "
                               + 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.
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments