内部类
1、内部类中的类只能通过外部类调用,内部类可以访问外部类的私有属性。
2、内部类分为成员内部类(静态内部类,非静态内部类),匿名内部类(用于只调用极少次数的类,省去声明类的过程,直接在内部写,如监听器),局部内部类(用的极少,即定义在方法内部),基本语法在下方代码中体现(不含局部内部类)。
package cn.ldedu;
/**
* 测试内部类
* @author Lenovo
*
*/
abstract class people{ //此处用于下方匿名内部类调用,不一定非要用抽象类,普通类也可以
abstract void eat();
}
public class testInClass{
int shape=0;
static int age=10;
class In{
int shape=1;
public void show(){
System.out.println("shape="+shape);//访问自己的shape
System.out.println("shape2="+testInClass.this.shape);//访问外部类的shape
System.out.println(age);
}
}
static class temp{
static int shape=3;
public void show(){
System.out.println(age); //只能访问外部类的静态变量或方法
System.out.println("shape="+shape);//访问自己的静态shape
}
}
public static void main(String[] args) {
testInClass ti=new testInClass();
In i=ti.new In(); //非静态内部类初始化规则
temp t=new testInClass.temp();//静态内部类初始化规则
i.show();
t.show();
people tt=new people(){ //匿名内部类
public void eat(){
System.out.println("eat hahah");
}
};
tt.eat();
}
}
运行截图如下: