一、内部类
1.内部类概述
2.内部类的四种实现形式
1.成员内部类
public class Outer {private int age=99;public static String a;//成员内部类public class Inner{private int age=88;private String name;
// public static String school; //jdk 16开始才支持定义静态成员变量public Inner() {}public Inner(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void test(){int age=66;//66System.out.println (age);//88System.out.println (this.age);//只能访问内部类中的属性//99System.out.println (Outer.this.age);//通过类名.this 访问外部类的属性}public void test2(){//成员内部类可以访问外部类的成员变量System.out.println (a);System.out.println (age);}}}
2.静态内部类
public class Outer {private int age;public static String schoolName;//静态内部类//类有的东西静态内部类都有public static class inner{private String name;public static int a;public void test(){//静态内部类可以直接访问外部类的静态成员变量System.out.println ( schoolName );//不能直接访问外部类的成员变量
// System.out.println ( age );}public String getName() {return name;}public void setName(String name) {this.name = name;}public static int getA() {return a;}public static void setA(int a) {inner.a = a;}}public static void test2(){//静态方法可以直接访问自己类的静态成员变量System.out.println (schoolName);//age 是对象的成员变量不能直接去访问
// System.out.println ( age );}
}
3.局部内部类
4.匿名内部类
1.什么是匿名内部类
2.匿名内部类在开发中的使用场景
public class Test {public static void main(String[] args) {Swimming s1=new Swimming (){@Overridepublic void swim() {System.out.println ("狗游泳");}};go (new Swimming (){@Overridepublic void swim() {System.out.println ("狗游泳");}} );go ( s1 );}//设计一个方法,可以接受Swimming接口的一切实现类进来参加游泳比赛public static void go(Swimming s){System.out.println ("开始----------------");s.swim ();}
}//猫和狗都要参加游泳比赛
interface Swimming{void swim();
}