×

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

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

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

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.