Java inner class review

"Java inner class", There were many places I didn't know that I knew unexpectedly, so let's review it.

What is an inner class?

As the word says, it is a class inside the class.

Inner class usage

As an application, it provides better concealment (encapsulation). You can hide classes that are meaningless away from the outer class. 例:Cow.javaとCowLeg.java

Classification of inner classes

  1. Non-static inner classes are associated with __outer class instances __
  2. Static inner class is related to __outer class __
  3. The local inner class is associated with the __ method __

Which one is relevant is very important and It turned out that the usage was decided.

Features of non-static inner classes

It is treated the same as non-static fields, methods, constructors, etc. of external classes. ⇒ Items that cannot be used unless the instance exists.

Private and protected can be used even though it is a class

(You can also add static, but it will be a static inner class, so later)

private,protected visibility


public class Outer {
    public class PublicInner {}
    private class PrivateInner {}
    public class PackagePrivateInner {}
}
  1. The upper unit of class is package, and public and package private are sufficient.
  2. Since the superordinate unit of the non-static inner class is the outer class, all visibility can be used.

The inside can see the outside, but the outside cannot see the inside

Visibility


public class Outer {
    private int outerVal;

    public class Inner {
        public int innerVal;
        private void method() {
            // OK
            this.innerVal = Outer.this.outerVal;
        }
    }

    private void method() {
        // NG
        // this.outerVal = innerVal;
    }
}

Non-static inner classes are associated with __outer class instances __, so

  1. "There is a non-static inner class instance = there is an outer class instance" ⇒ You can see the outside from the inside
  2. "The outer class instance exists. The non-static inner class instance exists." ⇒ The inside cannot be seen from the outside

Instantiation of non-static inner class

Instantiation of non-static inner class


Outer.Inner inner = (new Outer()).new Inner();
  1. (new Outer ())-> instance of external class
  2. Outer class .new Inner ()-> Instantiate a non-static inner class inside an instance of the outer class

Instances of non-static inner classes are exposed to outer classes

Access from external class


public class Outer {
    private int outerVal;

    public class Inner {
        private int privateA = 1;
        protected  int protectedB = 2;
        public int publicC = 3;
    }

    private void method() {
        Inner inner = new Inner();

        System.out.println(inner.publicC);
        System.out.println(inner.protectedB);
        System.out.println(inner.privateA);
    }
}

Access from other classes


public static void main(String[] args) {
    Outer.Inner inner = new Outer().new Inner();
    System.out.println(inner.publicC);
    System.out.println(inner.protectedB);
    
    // NG
    // System.out.println(inner.privateA);
}

An instance of an inner class

  1. Even private can be seen from the external class
  2. Visibility works from other classes

Why you can see Inner private from __Outer: __ inner-private.png

Outer$Inner@461 I understand that Inner is not independent, but part of Outer. Therefore, since it is in the same class, Private of Inner can also be seen in Outer. The same was true for static inner classes.

__ I'm looking for a better interpretation! !! !! __

Static field, method, block cannot be used

Compile error: 「Inner classes cannot have static declarations」

static members are NG


public class Outer2 {
    public class Inner {
        static { /** something **/ }
        public static int staticValue;
        public static void staticMethod() { /** something **/ }
    }
}

Non-static inner classes are associated with __outer class instances __, so 1.Since static is for associating with a class, not an instance Compile error because it is inconsistent in terms of grammar

Variable precedence

Variable precedence


public class Outer {
    String a = "outer-a";
    String b = "outer-b";
    String c ="outer-c";

    public class Inner {
        String a = "inner-a";
        String b = "inner-b";
        private void method() {
            String a = "method-a";

            System.out.println(a);
            System.out.println(b);
            System.out.println(c);

            System.out.println(this.a);
            System.out.println(Outer.this.a);
        }
    }

    public static void main(String[] args) {
        new Outer().new Inner().method();
    }
}
method-a
inner-b
outer-c
inner-a
outer-a

The priority of non-static inner classes is

  1. Local variable in the method
  2. Inner class instance variable
  3. Instance variables of external classes

You can specify the variable range with this.variable, Outer.this.variable. var-priority.png You can see from this debugged figure! !!

Features of static inner class

It's just like a regular class! !! However, it also has its own characteristics as an inner class.

Private and protected can be used even though it is a class

Like the non-static inner class, the upper level is a class, so private and protected can be used.

Instances of static inner classes are completely visible from outer classes

Because it belongs to the outer class as well as the non-static inner class.

Instantiation of static inner class

Instantiation of static inner class


Outer.Inner inner = new Outer.Inner();
  1. new outer class. Can be generated by static inner class ()

local inner class

python


public static void main(String[] args) {
    class Inner {
        protected int a = 1;
    }
    class InnerSub extends Inner {
        private int b = 2;
    }
    InnerSub sub = new InnerSub();
    System.out.println(sub.a + sub.b);
}
  1. Just as private and protected are not required for local variables, __visibility cannot be used __
  2. __static cannot be used because it is related to the method __

Summary

  1. When using an inner class, it is important to clarify __ "what (class, instance, method) you want to associate with" __.
  2. As a general rule, it is recommended that the inner class be static. The main reason is that non-static inner classes implicitly reference instances of enclosing classes (top-level classes). (Security ??) "this $ 0"

inner-private.png

From Effective Java 2nd Edition (The Java Series)

Recommended Posts

Java inner class review
Java class methods
[Java] Class inheritance
java Scanner class
Java HashMap class
java (abstract class)
[Java] Nested class
Java anonymous class
About Java class
[java] abstract class
[Java] Object class
Java local class
Java IO review
About class division (Java)
About Java StringBuilder class
NIO.2 review of java
Review of java Shilber
[Java] About Singleton Class
Java NIO 2 review notes
Inner class usage example
Java class type field
Java programming (class method)
About Java String class
A quick review of Java learned in class
Review Java annotations now
NIO review of java
Java programming (class structure)
Review java8 ~ Lambda expression ~
About java abstract class
A quick review of Java learned in class part4
A quick review of Java learned in class part3
A quick review of Java learned in class part2
[Java] Integer wrapper class reference
Java memo (standard class) substring
Java tips --StaticUtility class modifier
Progate Java (Beginner) Review & Summary
Java inflexible String class substring
Java memo (standard class) length
[Implementation] Java Process class notes
Java Collections Framework Review Notes
About Java class loader types
[Java] Comparator of Collection class
Java class definition and instantiation
Java learning memo (abstract class)
Summary of Java Math class
[Java] What is class inheritance?
About Java class variables class methods
[Java basics] What is Class?
Create an immutable class with JAVA
Why are class variables needed? [Java]
Call Kotlin's sealed class from Java
[Java] Object-oriented syntax --class method / argument
Various methods of Java String class
[Java] Memo for naming class names
How to disassemble Java class files
Kotlin Class to send to Java developers
StringBuffer and StringBuilder Class in Java
How to decompile java class files
[Java] How to use LinkedHashMap class
java (use class type for field)
Java