java - 基础 - 内部类
内部类:
java将一个类定义在另一个类的内部
如果一个类A只有在B里用到了,可以把A设为B的内部类
1.成员内部类
在类的内部,和类的成员同级(属性,方法,块)
2.局部内部类
在类的成员内,和局部变量统计(块,方法)
3.匿名内部类
没有类名,一般用来重写接口和抽象类的方法
4.静态内部类
成员静态内部类
package innerClass; public interface interfaceSchool { public void show(); }
package innerClass; public class School{ private String name; public static String location; School(String name){ this.name = name; } public String getName(){ return this.name; } public void innerClassTest(){ class localInnerClass{//局部内部类类似于局部变量,一般不会用到,不能用private public等修饰,可以用abstract和final修饰,使用的变量只能用final } } public class Student{ //成员内部类 public String name; public String schoolName; Student(String name){ Student.this.name = name; schoolName = School.this.name; //可以直接调用外部类的私有属性 } } public static class StaticStudent{//静态内部类 public static String name; public static String location; StaticStudent(String name){ StaticStudent.this.name = name; StaticStudent.this.location = School.location; //静态内部类只能访问静态成员 } } }
package innerClass; import innerClass.School.Student;//不在这里引用的话下面写成School.Student stu1 = sch1.new Student("studentname1");也可以 import innerClass.School.StaticStudent;//静态内部类和成员内部类导入方法一样 public class Test { public static void main(String[] args){ //先定义外部类再构造内部类 School sch1 = new School("schoolname1"); Student stu1 = sch1.new Student("studentname1"); //合并成一句 Student stu2 = new School("schoolname2").new Student("studentname2"); System.out.println(stu1.name); System.out.println(stu1.schoolName); System.out.println(stu2.name); System.out.println(stu2.schoolName); //匿名内部类, 通常是接口的子类,开发中可以省略一个类文件,相当于一个子类继承了School,一般用于接口的重写。 interfaceSchool sch3 = new interfaceSchool(){ public void show(){ System.out.println("我是一个匿名类重写的方法"); } }; sch3.show(); //静态内部类的使用 System.out.println("------Static------"); School sch4 = new School("schoolname4"); StaticStudent StaticStu1 = new StaticStudent("StaticStudent1"); //静态内部类可以直接声明 System.out.println(StaticStu1.name); System.out.println(StaticStu1.location); School sch5 = new School("schoolname4"); sch5.location = "bbb"; StaticStudent StaticStu2 = new StaticStudent("StaticStudent2"); System.out.println(StaticStu2.name); System.out.println(StaticStu2.location); System.out.println(StaticStu1.name);//因为属性是静态的,所以共享改变 System.out.println(StaticStu1.location);//因为属性是静态的,所以共享改变 } }