Introduction to Java nested classes

Hi! This article is dedicated to an important concept in Java object-oriented programming-nested classes. Simply put, a nested class is a class defined in another class (outer class). They are used to provide a higher level of encapsulation and organize logic code, which is only used in one place. In GUI development (for example, in Android programming), you will also encounter nested classes. Finally, if you really want to pass the Oracle exam, you must master nested classes as tasks in two stages.

In this article, we will observe what is a nested class in Java and the specific type of this class.

What is a nested class?

From a technical point of view, a nested class is a class, defined in another class. Outer classes are also called closed classes. These classes enable developers to logically group classes that are only used in one place, so this will increase the degree of encapsulation and create more readable and maintainable code. Nested classes in Java are divided into two categories: static and non-static. First group are also called static nested classes. Non-static nested classes are known as inner classes. Take a look on the graph below, that demonstrates an hierarchy of Java nested classes:

There are several parameters for using nested classes:

  1. When a class is only useful for another class, it is logical to embed it in the class and keep the two together. It is logical to nest small classes in top-level classes to make the code closer to where it is used. The use of nested classes is increased Powerful measures at the package level

These types of nested classes vary according to scope, access to closed class members, etc. Now, we will study them more deeply. We will start with static nested classes.

Static classes

The first group to be discussed is a static nested class group.

Static nested classes

Static nested classes are associated with their closed classes. It cannot directly reference instance variables or methods defined in its enclosing class-in other words, you must use object references. Let us look at the following example:

class Outer{

    static class Nested{

    }
}

// create nested class instance
Outer.Nested nestedInstance = new Outer.Nested();

Note that in the example code, the external class name is used to access the static nested class. Nested classes cannot access non-static data members, and methods of external classes can access static data members of external classes, including those declared private. Take a look at another code snippet:

class Car{

//static members
    static String manufacturer;
    private static String vin;

// instance member
    String model;


    static class Engine{
        System.out.println(manufacturer);
        System.out.println(vin);

    //This will be a compilation error
        System.out.println(model);
    }
}

So, what should static static classes remember? The following points:

  • Static nested classes can access static members of the outer class. They can't access instance (non-static) members of the outer class. Use only object references (like nesting). Static nested classes are created as OuterClass.StaticNestedClass nestedObject = new OuterClass .StaticNestedClass ();

Instead, there are several types of non-static inner classes.

Non-static classes

Non-static classes are associated with instances of closed classes, and you can directly access the methods and fields of closed classes. Moreover, since the inner class is associated with an instance of the outer class, it cannot itself define any static members. Let's observe the types of non-static classes.

Local inner classes

A local inner class is a class defined in a block, which is a set of zero or more statements between balanced brackets. Usually, these classes are defined within methods, but you can define partial classes within any block. Let us observe the following code:

class Outer{

    int value = 10;

    void calculate(){

        class Sum{

            int value;

            Sum(int a, int b){
                this.value = a + b;
            }

            int getValue(){
                return this.value;
            }
        }

        Sum sum = new Sum(20,30);
        System.out.println(sum.getValue());
        System.out.println(value);
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.calculate();
    }
}

Therefore, this example demonstrates occlusion: if a type declaration (such as a member variable or parameter name) in a specific scope (such as an inner class or method definition) has the same name as another declaration in a closed scope, the declaration will be closed Scope statement. In the example, we have two value variables and reference the keyword of the Sum member we use. Type declarations (such as variables) in the local class will have the same name in the shaded declaration in the enclosed scope.

Talking about local internal classes, and talking about access are also important local variables. Let us modify the above code:

void calculate(){

    int y - 10;

    class Multiplicator{

        int x;

        Sum(int x){
            this.value = x * y;
        }

        int getValue(){
            return this.value;
        }
    }

    Multiplicator multiplicator = new Multiplicator(10);
    System.out.println(multiplicator.getValue());
}

How can Multiplicator class access a local variable y? This is a popular interview question. Local classes can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter. But that how it was before Java 8. However, in the 8th release was introduced a concept of effectively final varialbes: these are variables or parameters whose value is never changed after it is initialized.

But in fact, the final variables do not need to be final anyway, the keywords in front of them cannot be changed after initialization. Following this principle, this code snippet will not compile:

void calculate(){

    int y - 10;

    class Multiplicator{

        int x;

        Sum(int x){
            this.value = x * y;
        }

        int getValue(){
            return this.value;
        }
    }

    y = 20;

    Multiplicator multiplicator = new Multiplicator(10);
    System.out.println(multiplicator.getValue());
}

When we try to compile it, Java will indicate an output similar to this error:

Let us summarize what we have learned so far about local internal classes:

  • The local internal class scope is the block that defines it. It cannot be instantiated from outside the block that created it. It can access local variables (if they are final (before Java 8) or actually final). The local internal class has access to it Member of the class

Similarly, partial inner classes can extend abstract classes and can also implement interfaces.

Anonymous classes

Finally, let's explore anonymous classes. From a technical point of view, they are like local inner classes, except that they have no name. Therefore, we only use them when we need to overload the methods of a class or interface without actually extending (implementing) them. Let us look directly at an example:

void doWork(){
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello runnable");
        }
    };
    runnable.run();
}

We implemented an internal interface that can run directly in the method that calls it. This can make the code more concise. We can declare and instantiate a class at the same time. You can declare fields and other methods that do not exist inside the parent class or interface inside the anonymous class, and you can even add local classes. However, you cannot declare a constructor in an anonymous class.

Important things to remember about anonymous classes:

  • They can access the members of their enclosed class the same as the local inner class, they cannot access local variables that are not declared final or valid final within their enclosed scope. Like nested classes, type declarations (such as variables) in anonymous classes obscure any other declarations with the same name in the enclosed scope. Anonymous classes can have static members, provided they are constant variables

Conclusion

In this tutorial, we explored different types of nested classes in Java. This topic is very important, so if you seriously consider passing the Oracle exam, you must master nested classes and have them as tasks in both phases. We discussed how to use and restrict them.

References

  • J Steven Perry Unit 18: Nested classes (2016) IBM Developer, read here
  • Manoj Debnath Understanding Java Nested Classes and Java Inner Classes (2017) Developer.com, read here

from: https://dev.to//andreevich/introduction-to-nested-classes-in-java-3d4a

Published 0 original articles · liked 0 · visits 419

Guess you like

Origin blog.csdn.net/cunxiedian8614/article/details/105689987