Java内部类
2015-12-12 21:15
375 查看
Java内部类
1、内部类的访问规则
外部类要访问内部类,必须建立内部类对象。/** * */ package ex01; /** * @author husheng * */ class Outer//外部类 { private int x = 3; class Inner//内部类 { int x = 4; void function() { int x = 6; System.out.println("hello world!"); } } void method() { Inner in = new Inner(); in.function(); } } class ex01//外部其他类 { public static void main(String[] args) { Outer out = new Outer(); out.method(); } }
内部类可以直接访问外部类中的成员,包括私有。
/** * */ package ex01; /** * @author husheng * */ class Outer//外部类 { private int x = 3; class Inner//内部类 { int x = 4; void function() { int x = 6; System.out.println("x="+x); } } void method() { Inner in = new Inner(); in.function(); } } class ex01//外部其他类 { public static void main(String[] args) { Outer out = new Outer(); out.method(); } }
我们依次把输出语句改为:
System.out.println("x="+x);
System.out.println("x="+this.x);
System.out.println("x="+Outer.this.x);
直接访问内部类中的成员。
class Outer//外部类 { private int x = 3; class Inner//内部类 { int x = 4; void function() { int x = 6; System.out.println("hello world!"); } } } class ex01//外部其他类 { public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.function(); } }
2、静态内部类
内部类就具备static的特性。在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员呢?
Outer.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的。
当外部类中的静态方法访问内部类时,内部类也必须是static的。
3、局部内部类
内部类定义在局部时,不可以被成员修饰符修饰。可以直接访问外部类中的成员,因为还持有外部类中的引用。但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。/** * */ package ex01; /** * @author husheng * */ class Outer { void method(final int a) { class Inner { void function() { System.out.println(a); } } new Inner().function(); } } class ex01 { public static void main(String[] args) { Outer out = new Outer(); out.method(7); out.method(8); } }
4、匿名内部类
匿名内部类其实就是内部类的简写格式。定义匿名内部类的前提:内部类必须是继承一个类或者实现接口。
匿名内部类的格式: new 父类或者接口(){定义子类的内容}
其实匿名内部类就是一个匿名子类对象。
/** * */ package ex01; /** * @author husheng * */ abstract class AbsDemo { abstract void show(); } class Outer { public void function() { new AbsDemo() { void show() { System.out.println("hello world!"); } }.show(); } } class ex01 { public static void main(String[] args) { new Outer().function(); } }
====================================================================================
结束。
相关文章推荐
- MyEclipse使用SVN进行项目版本控制
- [javase学习笔记]-3.4 for语句
- org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for
- java RC4加密和解码
- javaweb学习总结(三十九)——数据库连接池
- java多线程学习笔记——详细
- Java NIO 与 IO的区别
- 接口(Java)
- JAVA封装思想导论(猜字谜游戏2.0)
- JAVA封装思想导论(猜字谜游戏2.0)
- JAVA实现遗传算法
- Java并发编程学习笔记(一)——线程安全性
- Lombok 安装、入门 - 消除冗长的 java 代码
- [javase学习笔记]-3.3 while和do-while语句
- Java数组自定义比较器
- MyEclipse创建web工程,工程名出现红色感叹号
- java oop
- java多线程多人聊天的server
- JAVA异常处理
- maven中如何指定jdk的版本