Nested Class Summary Induction

Nested Class Summary Induction


提示:以下是本篇文章正文内容,下面案例可供参考

1. Concept

Nested classes: The focus is on nesting, where a class is defined inside another class

//文件名 B.java
//A类在B 类中定义,嵌套
public class B{
    
    
    Class A{
    
    
    }
}

//文件名 D.java
//类C 和 D 是并列的,无从属关系
//这不属于嵌套
class C {
    
    
}

public class D{
    
    

}

Second, the classification of nested classes

Nested classes: Nested classes

  • Static nested class: Static nested classes, that is, there is a static modifier in front of the class
  • Non-static nested classes: Non-static nested classes, also known as inner classes , Inner classes
    1. Ordinary inner classes (or translated into member inner classes)
    2. Local inner classes (Local classes)
    3. Anonymous inner classes (Anonymous classes)

Detailed URL: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Code display:

  • static nested class
public class Outer1{
    
    
      String name;
      //静态嵌套类
      static class Innerq{
    
    
      
      }
}
  • common inner class
public class Outer2{
    
    
      String name;
      //普通内部类/成员内部类
      public class Inner2{
    
    
      
      }
}
  • Local inner class (put in member method, such as inside a for statement, inside an if statement)
public class Outer3{
    
    
     String name;
     //局部内部类
     public void f1(){
    
    
          class Inner3{
    
    
               String name;
          }
     }
}
  • anonymous inner class
public class Outer4{
    
    
		Srting name;
		//匿名内部类
		public void f1(){
    
    
		     new Thread(new Runnable () {
    
    
		         public void run(){
    
    
		            System.out.println("hello");
		         }
				}).start();
		}
}
//这里的 Thread 为一个线程类 ,new Runnable 实现了一个匿名内部类,这个匿名内部类只能使用一次,下次使用只能重新new 

Why do you need nested classes? ?

  • Different access permission requirements, finer-grained access control
  • Concise, avoid too many class definitions
  • The language design is too complex, it is difficult to learn and use (there are disadvantages of nested classes)

3. Learn more about the four major nested classes

Nested class learning focus:

  • Nested class syntax
  • The relationship between nested classes and other classes
    1. Nested classes access outer enclosing classes
    2. Outer enclosing classes access nested classes
    3. Third-party classes access nested classes

Anonymous inner class: Anonymous classes

  • An inner class without a class name must inherit a parent class/implement a parent interface
  • After instantiation, quickly transform to the parent class/parent interface
  • This type of object can only be a new object, and then operate with the object name
  • Inner classes can be used in ordinary statements and member variable assignments
Runnable r = new Runnable(){
    
    
		public void run(){
    
    
				System.out.println("hello");
		}
}

new Thread(r).start();
package com;

public class Outer1 {
    
    
    private String name = "abc";

    //匿名内部类
    public void f1(){
    
    
        String name = "def";
        Runnable r = new Runnable() {
    
    
            //匿名内部类不能定义静态变量,除非是常量
            public final static int a = 5;
            String name = "ghi";
            @Override
            public void run() {
    
    
                System.out.println("hello :"+ name);
                //访问外部成员类的字段
                System.out.println("hello :"+ Outer1.this.name);
            }

            //静态方法不能再匿名内部类定义
            /*public static void f2(){

            }*/
        };

        new Thread(r).start();
        System.out.println(r.getClass().getName());
    }
}

Re-summarize its characteristics:

  • Internal class without official class name
    Compiled internal name: class name + $ + number
  • No class name, no constructor , the constructor of the parent class/parent interface can be used (with parameters)
  • Methods that can be inherited, rewritten, and supplemented by the parent class/parent interface
  • Static members (variables + methods) cannot be redefined internally, except for constants
    final static int a = 5;
  • Member variables and methods (including private) of the outer enclosing class can be accessed
  • If it is defined in a static method, it can only access the static members of the outer enclosing class
  • Without a class name, the outer enclosing class and other classes cannot access the anonymous inner class

Local inner classes: Local classes

  • Non-static classes defined in code blocks, such as methods, for loops, if statements, etc.
  • Once defined, objects can be created using
  • Can only live in this code block. After the code block ends, the outside world cannot use this class
public void f1(){
    
    
     String name = "def";
     class Inner2{
    
    
         public void f2(){
    
    
           System.out.println(name);
           System.out.println(Outer2.this.name);
         }
     }
     Inner2 obj1 = new Inner2();
     obj1.f2();
}

Features:

  • Compiled name: external class name + $ + serial number + internal class name
  • Can inherit other classes, or implement other interfaces
  • Non-static classes cannot contain static members (variables + methods), except constants
  • Members of the outer enclosing class can be accessed
  • If defined in a static method, only the static members of the enclosing class can be accessed
  • A local inner class cannot be an interface, that is, an interface cannot be defined in a code block

Ordinary inner class:

  • Non-static class, defined in the member variable position of a class
  • After definition, it can be used in the class
public interface Flyable {
    
    
    public void fly();
}

public abstract class Animal {
    
    
    public abstract  void eat();
}

#上面两个一个为接口,一个为抽象类,和下面代码是分开的


public class Outer3 {
    
    
    String name = "aaa";
    public class Bird extends Animal implements Flyable{
    
    
        public final static int a = 3;//常量OK
        @Override
        public void eat() {
    
    
            System.out.println("I can fly");
        }

        @Override
        public void fly() {
    
    
            System.out.println("I can fly" + name);
        }
    }
    public Bird obj = new Bird();
    public void f1(){
    
    
        obj.fly();
        System.out.println(obj.getClass().getName());
        this.name = "bbbb";
        obj.fly();
    }
    public Bird getBird(){
    
    
        return this.obj;
    }
}



Features:

  • Compiled name: external class name + $ + internal class name
  • Can inherit other classes, or implement other interfaces
  • You can use private / default (not write) / protected / public to control external access
  • Non-static classes cannot contain static variables/methods, except constants
  • Related to the instance of the outer enclosing class, an instance of an ordinary inner class must be in an instance of the outer enclosing class, and can access all members of the outer enclosing class.
  • In the third-party class, you need to create an instance of the outer enclosing class before you can create an instance of the ordinary inner class. Separate ordinary inner class objects are not allowed to exist! ! !

Static nested class:

  • The hierarchy is the same as the member variables/methods of the enclosing class
public class Outer1{
    
    
      String name;
      //静态嵌套类
      static class Inner1{
    
    
         String name;
      }
}
  • Third parties can only access static nested classes through the outer enclosing class
  • Outer1.Inner1 obj = new Outer1.Inner1();

Features:

  • Need to add modifier static
  • Can define static members and non-static members
  • You cannot directly access the non-static members of the enclosing class, you can directly access the static members of the enclosing class
    Non-static members can be accessed through the enclosing class object
  • The outside world can access its static members through static nested class names, and its non-static members through objects
  • The outside world needs to pass through the enclosing class to access the static nested class and create its objects, and does not need an instance of the external enclosing class.

insert image description hereinsert image description here
insert image description here

4. Variable masking

Variable shadowing: Shadowing

If the nested class variable has the same name as the variable of the outer enclosing class

  • Prioritize proximity
  • Variables with higher priority shadow lower priority variables
  • Outer enclosing class.this.Variable name, you can access the member variables of the outer enclosing class
  • Static nested classes cannot access non-static variables
  • Before Java7, anonymous inner classes and local inner classes could only access the final member variables of the outer enclosing class
  • After Java 8, anonymous inner classes and local inner classes can access the final member variables of the outer enclosing class and final variables in the de facto sense (effectively final, after a variable is defined, it has never been changed)

Guess you like

Origin blog.csdn.net/CXgeng/article/details/123425797