---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------
内部类
使用情况:但描述事物时, 事物的内部还有事物,该事物用内部类来描述
因为内部事务在使用外部事务的内容
内部类的访问规则:
1,内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类的成员,是因为内部类持有了一个外部类的引用,格式:外部类名.this
2, 外部类要访问内部类,必须先建立内部类对象。
访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,
可以在外部其他类中访问,需要直接建立内部类对象。
格式:
外部类名.内部类名 变量名 = 外部类对象.内部类对象
Outer.Inner in = new Outer().new Inner();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如 private:将内部类在外部类中进行封装。
static:内部类就具备static的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限。
在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员呢?
Outer.Inner.function();
注意:当内部类定义了static成员时,内部类必须声明为static的
当外部类的静态方法访问内部类是,内部类也必须是static的
实例代码:
class Outer
{
private int x = 3;
void method()
{
Inner in = new Inner();
in.function();
}
class Inner //内部类
{
int x = 4;
void function()
{
int x = 5;
System.out.println("inner:"+x);//函数内的局部变量x
System.out.println("inner:"+this.x);//内部类中的成员变量x
System.out.println("inner:"+Outer.this.x);//外部类的成员变量x
}
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
//Outer o = new Outer();
//o.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------