黑马程序员技术交流社区
标题:
java内部类
[打印本页]
作者:
viliv715
时间:
2014-8-25 09:18
标题:
java内部类
本帖最后由 viliv715 于 2014-8-26 18:01 编辑
/*
内部类:
a内部类可以直接访问外部类中的成员,包括私有成员.之所以可以访问外部类的成员
是因为内部类中持有了一个外部类的引用,格式:外部类名.this
b外部类要访问内部类中的成员必须要建立内部类的对象
访问格式:
a当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中直接建立内部类对象。
格式:
外部类名.内部类名 变量名 = 外部类对象.内部类对象
Outer.Inner in = new Outer().Inner();
b当内部类在成员位置上,就可以被成员修饰符修饰。
private:将内部类在外部类进行封装。
static:内部类就据别static的特征。当内部类被static修饰后,
只能直接访问外部类中的static成员,出现了访问局限。
注意:
当内部类出现了静态成员,内部类也必须是静态的。
当外部类中的静态方法访问内部类时,内部类也必须是静态的。
外部其他类直接访问静态内部类的非静态成员
new Outer().Inner().function();
外部其他类直接访问静态内部类的静态成员
Outer().Inner().function();
c内部类定义在局部时:
不可以被成员修饰符修饰
可以直接访问外部类中的成员,因为还持有外部类中的引用、
不可以访问它所在局部中的变量,只能访问被final修饰的局部变量。
*/
class Outer{
private int x = 3;
//内部类
class Inner{
int x = 4;
void function()
{
int x = 5;
//x=5
System.out.println("Inner:" + x);
//x=4
System.out.println("Inner:" + this.x);
//x=3
System.out.println("Inner:" + 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().Inner();
in.function();
}
}
复制代码
作者:
abc83983682
时间:
2014-8-25 09:26
总结的蛮到位的!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2