Nested class (for myself)

1. What is a nested class?

You can define more classes in the class definition, and the name is called nested class.

1-1. Features

It is simple and easy to read, and its use is limited, so it is common to apply it to classes that want to hide their existence from the outside.

1-2. Types of nested classes

Nested classes are divided into the following types.

--Nested class --static class --Inner class (non-static class) --[Local Class](# 2-Local Class) -[Anonymous class](# 3-Anonymous class)

1-3. Nested class rules

static/Non-static common -The same class name as the outer class cannot be used
-Access modifiers can be used.
・ Abstract/You can use the final modifier.
static class only ・ Non-static/Can have static members
-Unable to access the instance variable defined in the outer class
Non-static classes only -Cannot have static members
-You can access the instance variables defined in the outer class.

1-4. Compiling nested classes

Outer class name$Nested class name.class

1-5. Access to nested classes

Members in a nested class can be used by instantiating the nested class. It can be instantiated by the following method. [(1) Instantiate a nested class with an external class](# 1-5-1-Instantiate a nested class with an external class) [② Instantiate the nested class in the method of the outer class](# 1-5-2-Instantiate the nested class in the method of the outer class)

1-5-1. Instantiate a nested class with an external class

【syntax】 ・ For inner class (non-static class)


/***Outer class name.Inner class name variable name=
**new outer class name().new inner class name();
*/
Outer.Inner obj = new Outer().new Inner();

・ For static class


/***Outer class name.static class name variable name=
**new outer class name.static class name();
*/
Outer.StaticInner obj = new Outer.StaticInner();

1-5-2. Instantiate a nested class within a method of the outer class

An example of instantiating a nested class in the main method of the outer class and calling the members defined in the nested class.


class Outer{
  private int id = 100;

  class Inner {  //static method cannot be defined
    public int id = 200;
  //static void hogehoge(){...} //Compile error
    void method(int id){
      System.out.println("Local_scope_id" + id);
      System.out.println("Inner_scope_id" + this.id);
      System.out.println("Outer_scope_id" + Outer.this.id);
    }
  }

  static class Staticinner {  //Outer instance members are inaccessible
    public static int id = 300;
    static void method(int id){
      System.out.println(id);
      System.out.println(Staticinner.id);
    //System.out.println(Outer.this.id);  //Compile error
    }
  }

  public static void main(String... args){
  //Inner class instantiation and calling
    new Outer().new Inner().method(400);
  //new Inner().mehod(400);  //Compile error

    System.out.println();

  //Instantiation and calling of static classes
    new Outer.Staticinner().method(500);  //Basic syntax
    new Staticinner().method(600);  //Outer class name can be omitted
    Outer.Staticinner.method(700);  //new optional
    Staticinner.method(800);        //new,Outer class name can be omitted
  }
}

1-6. Nesting in interfaces and abstract classes + others

Nested classes also allow you to define interfaces and abstract classes


class Sample{
//Inherit
  abstract class A {abstract void foo();}
  class B extends A {void foo(){}}
//Implementation is also OK
  interface X {void hoge();}
  class Y implements X {public void hoge(){}}
/*Each of the above can be given static.
However, if you inherit the inner abstract class with a static class, a compile error will occur.(There is no problem implementing the inner interface with a static class)
Of course, static → static is also OK.
*/
}

You can also define nested classes within interfaces and abstract classes. Nested classes can also be defined ...

2. Local class

A class defined within a method of a certain class.

2-1. Features

-Valid only within the method (handled locally). -Since it is treated locally, access modifiers and static cannot be used. (That is, only non-static classes can be defined)

2-2. Local class rules

Local class -Access modifier(public,protected,private)Cannot be used
・static修飾子Cannot be used
-Abstract modifier and final modifier can be used.
-You can access the members of the outer class.

· To access the method arguments and local variables of the outer class from the local class, each variable is final(constant)Must. Therefore, until SE7, it was necessary to explicitly assign the final modifier, but from SE8, final is implicitly assigned, so it is not necessary to explicitly assign it.(In other words, it's a virtually final variable)

2-2. Sample code for local class


//Only local variables are effectively final

class Outer{
  private static int a = 1;  //static variable
  private int b = 2;  //Instance variables
  void methodOuter(int c, final int d){
    final int e = 5; int f = 6;
    class Local{
      void methodLocal() {
        System.out.println(a + "" + b + c + d + e + f);
      //c = 100;Compile error
      //d = 200;Compile error
      }
    }
    a = 10;  //OK
    b = 20;  //OK
  //e = 300;Compile error
  //f = 400;Compile error
    new Local().methodLocal();
  }

  public static void main(String... args){
    Outer obj = new Outer();
    obj.methodOuter(3, 4);
  }
}

//Execution result
10203456

[▲ Return to selection](# 1-2-Nest class type)

3. Anonymous class

A class in which the class definition and instantiation are described as one expression without specifying the class name.

3-1. Features

-Actually, it is a subclass of a certain class or a class that implements a certain interface, and the process (method) to be overridden after "new superclass" or "new interface" is described in the block. -Anonymous class is defined as one expression, so a semicolon is required at the end. -Use when you do not need to reuse and want to implement only in a specific location. Therefore, class definition and instantiation are performed at the same time without declaring the class name. -Although it can be used in a functional interface, lambda expressions that are easy to describe are the mainstream.

3-2. Anonymous class rules

Anonymous class -Access modifier(public,protected,private)Cannot be used
・ Cannot use static modifier
・abstract修飾子、final修飾子Cannot be used
· Can access members of outer classes
· Can access the method arguments and local variables of the outer class(However, implicit final)
-Cannot define constructor

3-3. Anonymous class definition example

-No object storage


class Sample1{
  private String name1 = "piyoko";  //Reassignable
  void method(String name2){  //Cannot be reassigned
    new MyInter(){
      public void piyo(){
        System.out.println(name1 + " & " + name2);
      }
    }.piyo();
  }
  public static void main(String... args){
    new Sample1().method("piyota");
  }
}

interface MyInter{
  void piyo();
}

・ With object storage


class Sample2{
  public static void main(String... args){
    MyInter obj = new MyInter() {
      public void hoge(String name) {
        System.out.println(name);
      }
    };
    obj.hoge("hogeta");
  }
}

interface MyInter{
  void hoge(String name);
}

//For lambda expression
MyInter obj = (name) -> {System.out.println(name);}; //Be careful not to forget to add a semicolon when enclosing in curly braces
MyInter obj = name -> System.out.println(name);

//Method reference
MyInter obj = System.out::println;

[▲ Return to selection](# 1-2-Nest class type)

References

-[Oracle Certification Textbook Java Programmer Gold SE 8 (EXAMPRESS)](https://www.amazon.co.jp/%E3%82%AA%E3%83%A9%E3%82%AF%E3%83 % AB% E8% AA% 8D% E5% AE% 9A% E8% B3% 87% E6% A0% BC% E6% 95% 99% E7% A7% 91% E6% 9B% B8-Java% E3% 83 % 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9E-Gold-SE-EXAMPRESS / dp / 479814682X)

end

Recommended Posts

Nested class (for myself)
[Java] Nested class
[For myself] Transfer of Servlet class processing
Gradle TIPS collection (for myself)
Summary of rails validation (for myself)
Enable OpenCV with java8. (For myself)
java (use class type for field)
Docker execution memo summarized for myself
docker single container restart for myself
A review note for the class java.util.Scanner
has_one association factory_bot accepts_nested_attributes_for request_spec [for myself]
Settings for running CGI programs locally (for myself)
A review note for the class java.util.Objects
Shape Scala case class for easy viewing