×

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

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

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

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

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

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.