参考视频:
https://www.bilibili.com/video/BV1Cv411372m?p=111&vd_source=c0cc92a482393bb63596629a72e3fc71
什么是内部类
内部类四种形式:
- 成员内部类
- 静态内部类
- 局部内部类
- 匿名内部类
成员内部类
代码示例: 成员内部类的定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
public class Outer { private int age = 99; private static String a; public class Inner{ private int age = 88; private String name; public static String schoolName;
public void test(){ System.out.println(age); System.out.println(a); int age = 66; System.out.println(age); System.out.println(this.age); System.out.println(Outer.this.age);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public static String getSchoolName() { return schoolName; }
public static void setSchoolName(String schoolName) { Inner.schoolName = schoolName; } } }
|
测试代码:
1 2 3 4 5 6 7 8 9 10
| public class Main { public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.getName(); in.setName("xxx"); in.test(); } }
|
笔记总结:
- 静态内部类
代码示例: 静态内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Outer2 { private int age; public static String schoolName;
public static class Inner{ private String name; private static int a;
public void test(){ System.out.println(schoolName); }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public static void test2(){ System.out.println(schoolName);
} } }
|
测试代码:
1 2 3 4 5 6 7
| public class Main { public static void main(String[] args) { Outer2.Inner in = new Outer2.Inner(); in.test(); } }
|
笔记总结:
5.局部内部类
了解即可
- 匿名内部类
匿名内部类在开发中的使用场景:
通常作为一个参数传输给方法
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class Test { public static void main(String[] args) {
Animal a = new Animal() { @Override public void cry() { System.out.println("mmm"); } };
go(new Swimming() { @Override public void swim() { System.out.println("狗游的快"); } }); }
public static void go(Swimming s){ System.out.println("开始-------"); s.swim(); } }
interface Swimming{ void swim(); }
abstract class Animal{ public abstract void cry(); }
|
笔记总结