×

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond, Heart, and Spade that fall under the umbrella of the enumerated type Suit. Natural enumerated types are another illustration 

When we know every potential value at compilation time, such as for menu options, rounded modes, command-line flags, etc., enums are employed. An enum type's set of constants need not always remain consistent over time.

A class type in Java is an enumeration. Although we don't need to use new to create an instance of an enum, it can still perform the same functions as other classes. The enumeration in Java is a very effective tool because of this aspect. They can have constructors, instance variables, and methods added, just like classes, and you can even create interfaces.

Keep in mind that enumerations cannot inherit from other classes or be expanded, unlike classes (i.e become superclass).

Enums are expressed in Java (as of 1.5) using the enum data type. Enums in Java are more capable than those in C/C++. Variables, methods, as well as constructors, can all be added to it in Java. Enum's primary goal is to allow us to create custom data types (Enumerated Data Types).

Example 1

enumColor {
	BLUE,
	GREEN,
	PINK;
}
public class Test {
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		System.out.println(c1);
	}
}

Output

BLUE

Example 2

Internally, each enum is implemented using a Class.

An object of the type enum is represented by each enum constant.

Switch statements accept arguments of the enum type.

import java.util.Scanner;
enum Day {
	SUNDAY,
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY;
}
public class Test {
	Day day;
	public Test(Day day) { this.day = day; }
	public void dayIsLike()
	{
		switch (day) {
		case MONDAY:
			System.out.println("Mondays are good.");
			break;
		case FRIDAY:
			System.out.println("Fridays are better.");
			break;
		case SATURDAY:
		case SUNDAY:
			System.out.println("Weekends are best.");
			break;
		default:
			System.out.println("Midweek days are so-so.");
			break;
		}
	}
	public static void main(String[] args)
	{
		String str = "MONDAY";
		Test t1 = new Test(Day.valueOf(str));
		t1.dayIsLike();
	}
}

Output

Mondays are good.

Example 3

Every enum constant is inherently public static final. The enum Name can be used to access it because it is static. We cannot make child enums because it is final.

The main() method can be declared inside the enum. So, using the Command Prompt, we can just call enum.

enumColor {
	BLUE,
	BROWN,
	PINK;
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		System.out.println(c1);
	}
}

Output

BLUE

Example 4

Enumerations and Inheritance

Implicitly, every enum extends Java.lang.

  • class enum. An enum never extends anything else, just as a class in Java could only extend one     parent.
  • In Java.lang, the function toString() { [native code] }() method is overridden.Theenum constant name is returned by the enum class.
  • Many interfaces can be implemented with enum.

The methods values(), ordinal(), and function valueOf()

  • These methods can be found in the Java.lang library.
  • All values contained within the enum can be returned using the enum.values() method.
    In enums, the order is crucial.
  • Every enum constant index can always be retrieved utilising ordinal() method, exactly like an array index.
  • If an enum constant for the provided string value exists, the function valueOf() { [native code] }() method returns it.
enumColor {
	PINK,
	GREEN,
	BLUE;
}
public class Test {
	public static void main(String[] args)
	{
		Colorarr[] = Color.values();
		for (Colorcol :arr) {
			System.out.println(col + " at index "
							+ col.ordinal());
		}
		System.out.println(Color.valueOf("PINK"));
	}
}

Output

PINK at index 0GREEN at index 1
BLUE at index 2
PINK

Example 4

function Object()  and enumerator

Enums are capable of having constructors, which are run independently for every enum constant when the enum class is loaded.

Enum objects cannot be explicitly created, and as a result, their function Object() { [native code] } cannot be called directly.

enum and procedures:

Enum is capable of including both concrete and abstract procedures. Every instance of an enum class that has an abstract data type must implement it.

enumColor {
	RED,
	GREEN,
	BLUE;
	private Color()
	{
		System.out.println("Constructor called for : "
						+ this.toString());
	}
	public void colorInfo()
	{
		System.out.println("Universal Color");
	}
}
public class Test {
	public static void main(String[] args)
	{
		Color c1 = Color.RED;
		System.out.println(c1);
		c1.colorInfo();
	}
}

Output

Constructor called for: RED
Constructor called for: GREEN
Constructor called for: BLUE
RED
Universal Color

Java Class

A class called Class is offered by Java and is part of the java.lanckage. Classes as well as interfaces in an active Java application are represented by instances of the type Class. Additionally, Class objects are used to represent the primitive Java types (byte, char, short, int, long, float, as well as double), as well as the keyword void. It doesn't have a public function Object(). The Java Virtual Machine generates class instances automatically (JVM). We cannot extend it since it is a final class.

The Reflection API frequently makes use of the Class class methods.

Class objects can be created in three different ways:

  1. Class.forName(“className”): Class.forName() is a static factory method that is present in class Class and is used to create objects of class Class because class Class lacks a function Object(). The syntax is as follows:
Class c = Class.forName(String className)

The sentence above creates a Class object for the class that was supplied as a String argument (className). Keep in mind that the className option must contain the whole name of the desired class for which the Class object is to be generated. Factory methods are another name for any Java method that returns an instance of the same class object. Run-time decision-making determines the abstract class for which a Class object is going to be constructed.

  • Myclass.class: Adding.class to a class name refers to the Class object which stands in for the specified class. When we know the name of the class, it is only utilized with primitive data types. At compile time, any class name wherein the Class object is now to be constructed is chosen. The syntax is as follows:
Class c = int.class

Please be aware that class names, not class instances, are utilized with this technique. For instance

Bb = new B();   
Class c = B.class; 
Class c = b.class;  
  • obj.getClass() : The Object class contains a method called obj.getClass(). This(obj) object's run-time class is returned. The syntax is as follows:
Bb = new B();   
Class c = b.getClass();

Class in Java

There is an enum class in the java.lang package. It serves as the foundational class for all enumeration types in Java. Enum in Java is a good resource for information on enums.

Declaring a Class

Enum is a public abstract class where E extends Enum. Comparable and Serializable Object

We cannot construct objects of the type Enum since, as we can see, it is an abstract class.

The enum class offers some helpful methods. The majority of them are Object class overrides. Since the Enum class declares these methods as final, the programme is unable to change one of the enum parameters.

1. final String name() :

enum constant's name, as defined in its enum declaration, is returned by the method's final String name().

Syntax:

public final String name()

No parameters: offer the name of that kind of enum constant as a response.

Example program

enumColor
{
BLUE,PINK,YELLOW;
}
public class Test
{
    public static void main(String[] args)
    {
Color c1 = Color.BLUE;
System.out.print("Name of  theenum constant: ");
System.out.println(c1.name());
    }
}

Output

Name of the enum constant: BLUE

2. final int ordinal()

Enumeration constant's index is returned by the method final int ordinal().

Syntax: 

public final int ordinal()

No parameters

  • returns: The value of this enumeration constant's ordinal

Example program

enumColor
{
	RED, GREEN, BLUE;
}
public class Test
{
	public static void main(String[] args)
	{
		Color c1 = Color.GREEN;
		System.out.print("ordinal of the  enum variable "+c1.name()+" : ");
		System.out.println(c1.ordinal());
	}
} 

Output

ordinal of the enum variable: 1

3. String toString():

This enumeration constant is represented as a String object by the function string function toString() . The name() method is equivalent to this one.

syntax

public String toString()

Parameters:

NA

Provide a textual representation of such an enumeration constant in its response.

Exceptions: to

enumColor
{
	RED, GREEN, BLUE;
}
public class Test
{
	public static void main(String[] args)
	{
		Color c1 = Color.GREEN;
		String str = c1.toString();
		System.out.println(str);
	}
}

Output

GREEN

4. final booleanequals(Object obj):

If the given object matches this enum constant, then this method returns true; otherwise, it returns false.

Syntax:

public final booleanequals(Object obj)

The object being compared to this enum for equality is indicated by the parameter obj.

If the given item matches this enum constant, it returns true, if not, false

Represents in class Object overrides

Example program

enumColor
{
	BLUE, YELLOW, PINK;
}
public class Test
{
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		Color c2 = Color.YELLOW;
		Color c3 = Color.PINK;
		
		boolean b1 = c1.equals(c2);
		boolean b2 = c1.equals(c3);
		boolean b3 = c2.equals(null);
		
	System.out.println("is c1 equal to c2 : " + b1);
		System.out.println("is c1 equal to c3 : " + b2);
		System.out.println("is c2 equal to null : " + b3);
	}
}

Output

is c1 equal to c2 : false
is c1 equal to c3 :false
is  c2 equal to null : false

5. final int hashCode() :

This method returns an enum constant's hash code as an outcome of the final int hashCode() function. The only statement in this method is "return super.hashCode()," which calls the hashCode() method of the Object class.

Syntax:

public final int hashCode()

Parameters:

NA

Obtains: an enum constant's hash code.

HashCode in the class Object is overridden.

Example program

enumColor
{
	BLUE, YELLOW, PINK;
}
public class Test
{
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		System.out.print("hashcode of enum constant "+ c1.name() +" : ");
		System.out.println(c1.hashCode());
		Color c2 = Color.YELLOW;
		System.out.print("hashcode of enum constant "+ c2.name() +" : ");
		System.out.println(c2.hashCode());
	}
}

Output

hashcode of enum constant BLUE : 705927765
hashcode of enum constant YELLOW : 366712642

Related Topics

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.