您的位置:首页 > 职场人生

黑马程序员-java内部类

2014-08-22 15:21 232 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
/*
内部类:
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();
}
}
<pre name="code" class="java">/*
匿名内部类:其实是内部类的简写形式。是一个匿名子类对象。
定义匿名内部类的前提:内部类必须是继承一个类或者实现接口。
匿名内部类格式:new 父类或者接口(){定义子类的内容}
*/
abstract class AbsDemo{
abstract void show();
}

class Outer{
private int x = 3;

public void method(){
//匿名内部类
//形式一
new AbsDemo()
{
void show()
{
System.out.println(x);
}
}.show();
//形式二
AbsDemo d = new AbsDemo()
{
void show()
{
System.out.println(x);
}
};
d.show();
}
}

class InnerClassDemo{
public static void main(string[] args){
Outer out = new Outer();
out.method();

//直接访问内部类成员
Outer.Inner in = new Outer().Inner();
in.function();
}
}

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: