×

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

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.