×

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

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.