JAVA学习:内部类
来源:互联网 发布:晋业进销存软件报表 编辑:程序博客网 时间:2024/05/21 17:39
一、内部类的访问规则:
1、内部类可以直接访问外部类中的成员,包括私有。格式为外部类名.this
2、外部类要访问内部类,必须建立内部类对象。
代码:
class Outer{private int x = 3;class Inner//内部类{//int x = 4;void function(){//int x = 6;System.out.println("innner :"+Outer.this.x);}}/**/void method(){Inner in = new Inner();in.function();}}class InnerClassDemo{public static void main(String[] args) {Outer out = new Outer();out.method();直接访问内部类中的成员。Outer.Inner in = new Outer().new Inner();in.function();}}
二、内部类访问格式:
1、内部类定义在外部类的成员位置上,而且非私有,就可以在外部其他类中建立内部类对象。
2、格式:外部类名.内部类名 变量名 = 外部类对象.内部类对象;
3、格式:Outer.Inner in = new Outer().new Inner();
4、当内部类在成员位置上,就可以被成员修饰符所修饰。比如,private
5、当内部类被static修饰后,只能直接访问外部类中的static成员。
注意:
1、在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
2、在外部其他类中,如何直接访问static内部类的静态成员呢?
outer.Inner.function();
3、当外部类中的静态方法访问内部类时,内部类必须是static的。
代码:
class Outer{private static int x = 3;static class Inner//静态内部类{static void function(){System.out.println("innner :"+x);}}static class Inner2{void show(){System.out.println("inner2 show");}}public static void method(){// Inner.function();new Inner2().show();}}class InnerClassDemo2{public static void main(String[] args) {Outer.method();Outer.Inner.function();new Outer.Inner().function();直接访问内部类中的成员。Outer.Inner in = new Outer().new Inner();in.function();}}
三、内部类定义在局部:
1、不可以被成员修饰符修饰
2、可以直接访问外部类中的成员,因为还有外部类中的引用。
3、但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
代码:
class Outer{int x = 3;void method(final int a){final int y = 4;class Inner{void function(){System.out.println(y);}}new Inner().function();}}class InnerClassDemo3{public static void main(String[] args) {Outer out = new Outer();out.method(7);out.method(8);}}
四、匿名内部类(其实就是内部类的简写格式):
1、内部类必须是继承一个类或者实现接口。
2、匿名内部类的格式: new 父类或者接口(){定义子类的内容}
3、其实匿名内部类就是一个匿名子类对象。可以理解为带内容的对象。
4、匿名内部类中定义的方法最好不要超过3个。
代码:
abstract class AbsDemo{abstract void show();}class Outer{int x = 3;class Inner extends AbsDemo{int num = 90;void show(){System.out.println("show :"+num);}void abc(){System.out.println("hehe");}}public void function(){AbsDemo a = new Inner();Inner in = new Inner();in.show();in.abc();AbsDemo d = new AbsDemo(){int num = 9;void show(){System.out.println("num"+num);}void abc(){System.out.println("haha");}};d.show();}}class InnerClassDemo4 {public static void main(String[] args) {new Outer().function();}}
- Java学习:内部类
- Java内部类学习
- java内部类学习!!
- java学习---内部类
- Java 内部类学习
- 【JAVA学习】内部类
- java学习-内部类
- java内部类学习
- JAVA学习:内部类
- JAVA学习-内部类
- JAVA学习--内部类
- JAVA内部类学习
- Java内部类学习
- Java学习:内部类
- java学习--内部类
- java 内部类学习
- 学习java内部类
- 学习Java内部类
- Ubuntu Server上的LVM配置
- 设计模式(二)单例设计模式
- JAVA学习:多态
- 《剑指Offer》面试题-二维数组中的查找
- “String.h” 源代码总结
- JAVA学习:内部类
- 《剑指Offer》面试题-从头到尾打印链表
- 《剑指Offer》面试题-重建二叉树
- JAVA学习:异常
- UVA 10194 - Football (aka Soccer)
- 《剑指Offer》面试题-用两个栈实现队列
- 第一个Delphi程序(Hello World)
- artDialog.js
- 浅析人脸检测之Haar分类器方法