Java inner classes (super detailed)

Before learning the inner class, let's first understand what are the five members of the class?

properties, methods, constructors, code blocks, inner classes

内部类就是在一个类或方法中定义的类。内部类又分为成员内部类,静态内部类,匿名内部类和局部内部类。

1. Member inner class

A member inner class is a class defined inside a class as a member of the class.

 
 

java

copy code

public class Outer { private Inner inner=null; private double r; String b; public Inner getInnerInstance(){//用于返回一个内部类对象 if (inner==null) inner=new Inner(); return inner; } private class Inner{//成员内部类,用private修饰,只能外部类的内部访问 final static int t=1;//成员内部类不能定义静态成员,final修饰的除外 public void draw(){ System.out.println("绘制一个圆,半径为"+r); } } }

The features are as follows:

  1. 内部类可以直接访问外部类的所有成员(成员变量和成员方法), including those modified by private and static. However, the outer class cannot directly access the members of the inner class, and needs to be accessed through the pre-created inner class object.
  2. Member inner classes can be modified arbitrarily with permission modifiers (private, default, protected, public).
  3. Members of the inner class contain a reference to the outer class object by default. To create a member inner class object, an outer class object must first be created.
  4. Member internal class object creation method:
 
 

java

copy code

//第一种方式 Outer outer=new Outer(); Outer.Inner inner=outer.new Inner(); //第二种方式 Outer.Inner inner1=outer.getInnerInstance();//在外部类提供一个方法,返回一个内部类对象

  1. When the member inner class has a member variable or method with the same name as the outer class, a hidden phenomenon will occur, that is, by default, the members of the member inner class are accessed. If you want to access a member of the same name of an external class, you need to access it in the following form:

External class.this.member variable/member method

  1. Static members of the outer class cannot access the inner class, and the inner class cannot define static members (except those modified by final), such as static methods, static properties, and static code blocks.

2. Static inner class

Member inner classes decorated with static are called static inner classes.

 
 

java

copy code

public class Test { public static void main(String[] args) { Outer.Inner inner=new Outer.Inner();//静态内部类可以被其他类直接访问和实例化,而不需要先实例化外部类。 inner.draw(); } } class Outer { int t=0; static String desc="123"; static class Inner{ static int x=10; { System.out.println("这里是静态内部类的代码块"); } public static void draw(){ System.out.println("t的值:");//这里会编译报错 System.out.println("desc的值:"+desc); } } }

The features are as follows:

  1. The static inner class can access the static members of the outer class, but cannot access the non-static members, and the inner class can also define static members.
  2. The static inner class is the only inner class among the four types that does not depend on the reference of the outer class object. The static inner class can be directly accessed and instantiated by other classes without instantiating the outer class first.

3. Anonymous inner class

An anonymous inner class has no explicit class name, is usually defined when creating an object, and can be used directly in an expression without declaring a named class separately. In the new features of jdk8, Lambda expressions can be used instead.

 
 

java

copy code

public class Test { public static void main(String[] args) { Calculator calculator=new Calculator() {// 创建一个匿名内部类实现Calculator接口 @Override public int calculate(int a, int b) { return a + b; } }; System.out.println(calculator.calculate(2,3)); } } interface Calculator { int calculate(int a, int b); }

匿名内部类可以出现在任何允许表达式出现的地方, such as method parameters, variable initialization, method return values, etc. Definition format:

new parent class constructor (parameter list) or implement interface ()
{ //class body part of anonymous inner class }

Features :

  1. The anonymous inner class can access all the variables and methods of the outer class, and cannot modify the outer local variables in the anonymous inner class.
  2. An anonymous inner class contains a reference to the outer class object by default.
  3. There is also a prerequisite for using anonymous inner classes : you must inherit a parent class or implement an interface
  4. Anonymous inner class can only be used once, it is usually used to simplify code writing.

Note: An anonymous inner class is the only class that does not have a constructor. Anonymous inner classes are used to inherit other classes or implement interfaces. It does not need to add additional methods, but only implements or rewrites inherited methods.

Use Lambda to replace

Lambda expressions cannot replace all anonymous inner classes. The basis for using Lambda is that there must be a corresponding functional interface (a functional interface refers to an interface with only one abstract method inside).

1. Shorthand for no-argument functions

If you need to create a new thread, write anonymous inner class:

 
 

java

copy code

new Thread(new Runnable(){// 接口名 @Override public void run(){// 方法名 System.out.println("Thread run()"); } }).start();

Simplified writing of Lambda expressions:

 
 

java

copy code

new Thread( () -> { // 省略接口名和方法名 System.out.print("Hello"); System.out.println("Jack"); } ).start(); //如果函数体只有一行语句,花括号直接去掉,留下那一行语句,比如() -> System.out.println("Thread run()")

2. Shorthand for functions with parameters

If you want to pass a custom comparator to a list of strings and sort them according to the length of the string, the anonymous inner class is written as follows:

 
 

java

copy code

List<String> list = Arrays.asList("I", "love", "you"); Collections.sort(list, new Comparator<String>(){// 接口名 @Override public int compare(String s1, String s2){// 方法名 if(s1 == null) return -1; if(s2 == null) return 1; return s1.length()-s2.length(); } });

Simplified writing of Lambda expressions:

 
 

java

copy code

List<String> list = Arrays.asList("I", "love", "you"); Collections.sort(list, (s1, s2) ->{// 省略参数表的类型 if(s1 == null) return -1; if(s2 == null) return 1; return s1.length()-s2.length(); });

custom function interface

To customize a function interface, you only need to write an interface with only one abstract method.

 
 

csharp

copy code

// 自定义函数接口 @FunctionalInterface //这个注解是可选的,但加上该标注编译器会帮你检查接口是否符合函数接口规范。 interface MyInterface<T>{ void doSomething(T t); } class Test<T>{ private List<T> list; public void myForEach(MyInterface<T> myInterface){ for (T t:list) { myInterface.doSomething(t); } } public static void main(String[] args) { Test test=new Test(); test.list= Arrays.asList(12,13,14,15,16,17); test.myForEach(str->System.out.println(str));// 使用自定义函数接口书写Lambda表达式 } }

*需要注意的是:*

The lambda expression implies the return keyword, so in a single expression, we don't need to explicitly write the return keyword, but when the expression is a statement set, we need to explicitly add return and use curly braces { } Surround multiple expressions, let's look at a few examples:

 
 

java

copy code

//返回给定字符串的长度,隐含return语句 (String s) -> s.length() // 始终返回42的无参方法 () -> 42 // 包含多行表达式,则用花括号括起来 (int x, int y) -> { int z = x * y; return x + z; }

4. Local inner class

局部内部类是定义在一个方法或者一个作用域里面的类,它和成员内部类的区别在于局部内部类的访问仅限于方法内或者该作用域内。Scope refers to the code block in the method (such as if/else statement block, for loop block, while loop block, etc.).

 
 

java

copy code

class Outer{ public void test(){ int x=20; class Inner{ //在方法内定义 public void print(){ System.out.println("我今年"+x); } } new Inner().print(); // 局部内部类必须在方法内部实例化,然后return出去或者直接调用其方法。 } public static void main(String[] args) { Outer outer = new Outer(); outer.test(); } }

The features are as follows:

  1. Local inner classes cannot have access modifiers and cannot be defined as static.
  2. The inner class can directly access all members of the outer class (member variables and member methods).
  3. Local inner classes contain references to outer class objects by default
  4. Local inner classes can also use the Outer.this syntax to formulate access to outer class members

5. The role of internal classes

  • Multiple inheritance can be achieved. (biggest advantage)
  • Inner classes provide better encapsulation, except for the outer class, no other class can access.
  • Inner classes have access to all elements of the outer class.
  • Within a single enclosing class, multiple inner classes can implement the same interface in different ways, or inherit from the same class.

Member inner classes implement multiple inheritance:

 
 

java

copy code

class Father { public int eat(){ return 10; } } class Mother { public int fly(){ return 20; } } class Son { class Father_1 extends Father{ public int eat(){ return super.eat() + 10; } } class Mother_1 extends Mother{ public int fly(){ return super.fly() - 7; } } public int geteat(){ return new Father_1().eat(); } public int getfly(){ return new Mother_1().fly(); } } public class Test { public static void main(String[] args) { Son son = new Son(); System.out.println( son.geteat()); System.out.println( son.getfly()); } }

Guess you like

Origin blog.csdn.net/BASK2312/article/details/132318829