首页  

java内部类     所属分类 java 浏览量 1067
把一个类的定义放在另一个类的内部
四种内部类
静态内部类 成员内部类 局部内部类 匿名内部类 

局部内部类 定义在方法中的内部类


匿名内部类特点
必须继承一个抽象类或者实现一个接口
不能定义任何静态成员和静态方法
不能是抽象的 
当方法的形参需要被匿名内部类使用时,必须声明为 final

内部类的优点
可访问外部类对象的成员
内部类对其他类不可见,具有很好的封装性
内部类可实现“多重继承” 
匿名内部类可以方便的定义回调




public class Outer{ private String name = "tiger"; static class StaticInner { public void hello() { System.out.println("StaticInner.hello() run"); } public static void sayHello() { System.out.println("StaticInner.sayHello() run"); } } class Inner { public void hello() { // 访问外部类私有成员 System.out.println("Inner.hello() run,Outer.name="+name); } // The method sayHello cannot be declared static; // static methods can only be declared in a static or top level type /* public static void sayHello() { System.out.println("Inner.sayHello() run"); } */ } public void methodHasInnerClass(){ int id = 3; // 局部内部类 定义在方法中的内部类 class InnerInMethod { private void hello(){ System.out.println("InnerInMethod.hello() run ,id="+id+",outer.name="+name); } } InnerInMethod inner = new InnerInMethod(); inner.hello(); } public void execute(){ int id = 9; // 匿名内部类 new Runnable(){ public void run(){ System.out.println("out.execute() run,id="+9); } }.run(); } }
public class Main{ public static void main(String[] args) throws Exception { Outer.StaticInner.sayHello(); Outer.StaticInner staticInner = new Outer.StaticInner(); staticInner.hello(); Outer outer = new Outer(); // 注意内部类 new 方式 Outer.Inner inner = outer.new Inner(); inner.hello(); outer.methodHasInnerClass(); outer.execute(); } }
内部类命名规则 外部类名字+$+内部类名字 Main.class Outer.class Outer$Inner.class Outer$StaticInner.class Outer$1.class Outer$1InnerInMethod.class
完整代码 https://gitee.com/dyyx/hellocode/tree/master/src/innerclass

上一篇     下一篇
OLAP术语

springboot中使用 JWT

java访问修饰符

java泛型

Linux Load 查看及计算

数据仓库术语