Enumerations are used to represent a set of named constants in programming languages. Enumerations are used when we know all possible values ??at compile time, such as menu selections, rounding modes, command line flags, etc. The set of constants in an enumeration type does not need to remain fixed all the time. In Java, enumerations are represented by the enum data type. Java enumerations are more powerful than C/C++ enumerations. In Java, we can also add variables, methods, and constructors to it. The main purpose of enum is to define our own data types (Enumerated Data Types). Instance variables are non-static variables, declared in any method, constructor, or class outside of the block.
Problem description :
Our problem is the way to use enum Constructor, Instance Variable & Method in Java.
So, for this solution, we'll see the below example initializes enum employing a constructor & totalPrice() method & display values of enums.
Code:
// 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.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.