×

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation easier to useand makescode easier to read and maintain. The scope of its enclosing class limits a nested class's scope. So in the following example, the NestedClass class does not exist independently of the OuterClass class.

Members of nested classes (including private members) can access nested classes. However, members of nested classes are not accessible from the outer class. The outer class of a nested class is also a member. As an individual of the containing class, the given class can be pronounced private, public, secure, or bundled-private (the default). There are two types of nested classes:

Nested static class:

A statically nested class is a nested class declared static. Inner circle: Non-static nested class are inner classes.

An inner class object of a regular or regular inner class cannot exist ifan outer class object already exists. In particular, inner-class objects always have a strong connection with outer-class objects. However, for static nested classes, a static nested class object can exist even if theouter class object does not.

Objects of statically nested classes do not strongly connect to objects ofouter classes. Statically nested classes are linked to their enclosing class, like class methods and variables. Like static class methods, statically nested classes cannot directly reference instance variables or methods defined in their enclosing class. It can only be used withobject references. The name of the enclosing class is used to come to them.

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClassnested object =new OuterClass.StaticNestedClass();
// Java program to demonstrate accessing
// a static nested class
// outer class
class OuterClass   {
    // static member
    static int outer_x = 10;    // instance(non-static) member
    int outer_y = 20;  
    // private member
    private static int outer_private = 30;
    // static nested class
    static class StaticNestedClass   {
        void display() {
            // can access static member of outer class
System.out.println("outer_x = " + outer_x);
            // can access display private static member of outer class
System.out.println("outer_private = " + outer_private);
            // The following statement will give compilation error
            // as static nested class cannot directly access non-static members
            // System.out.println("outer_y = " + outer_y);
}   }   }
// Driver class
public class StaticNestedClassDemo   {
    public static void main(String[] args)   {
        // accessing a static nested class
OuterClass.StaticNestedClassnestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();  }    }

Inner classes

// Java program to demonstrate accessing
// a inner class
// outer class
class OuterClass  {
    // static member
    static int outer_x = 10;
    // instance(non-static) member
    int outer_y = 20;
      // private member
    private int outer_private = 30;
    // inner class
    class InnerClass  {
        void display() {
            // can access static member of outer class
System.out.println("outer_x = " + outer_x);
            // can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
            // can also access a private member of the outer class
System.out.println("outer_private = " + outer_private);
}   }   }
// Driver class
public class InnerClassDemo   {
    public static void main(String[] args)  {
        // accessing an inner class
OuterClassouterObject = new OuterClass();
OuterClass.InnerClassinnerObject = outerObject.newInnerClass();
innerObject.display();}    }

Output:

outer_x = 10
outer_y = 20
outer_private = 30

Suppose you need to define a "department code" for each department enumeration constant. This code is alphanumeric, so store it as a string. The department enumeration allows you to create a private instance variable for the department code and a getter method to retrieve its value, just likea class definition. While defining the enumeration itself, wealso define a constructor that we pass in the department code.

The improved enumeration looks like this: It uses a constructor that accepts a department code when creating the enum, a getter method for deptCode called getDeptCode(), and a new private instance variable called deptCode that holds the department code.

public enum Department {
  HR("DEPT-01"), OPERATIONS("DEPT-02"), LEGAL("DEPT-03"), MARKETING("DEPT-04");//semi-colon is no longer optional here
Department(String deptCode){
this.deptCode=deptCode;
  }
  private String deptCode;
  public String getDeptCode(){
    return deptCode;
  }
}

Related Topics

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute 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.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

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

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute 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 max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.