/*
类部类可以直接访问外部类的变量
外部类要访问内部类必须建立内部类对象
一般用于类的设计,发现一般事务中还有事务
*/
class Outer
{
private int num=3;
class Inner //内部类 ,生成类名 Outer@Inner
{
void show()
{
System.out.println("hello Inner"+num);
}
static void function()
{
}
}
public void method()
{
Inner in=new Inner();
in.show();
}
}
//内部类的修饰符
/*
private public
直接访问内部类中的成员,必须描述一下所属
Outer.Inner in= new Outer().new Inner();
in.show();
static修饰
如果内部类是静态的,则相当于一个外部类
Outer.Inner in=new Outer.Inner();
static成员只能访问静态变量
内部类是静态的,其成员方法也是静态的
Outer.Inner.function();
非静态内部类内部之中不能够有静态方法
如果内部类有静态成员,则该内部类也必须是静态的
为什么内部类能够直接访问外部类的成员呢
因为内部类持有外部类的引用 Outer.this
class Outer
{
int num=3;
class Inner
{
int num=4;
void show()
{
int num=5;
System.out.println(num); //5
System.out.println(this.num); //4
System.out.println(Inner.this.num); //4
System.out.println(Outer.this.num); //3
}
}
void method()
{
new Inner().show();
}
}
*/
/*
内部类可以存放在局部位子上
*/
class Outer
{
int num=3;
void method()
{
final int x=3;
class Inner
{
void show()
{
//内部类访问该函数的局部变量,该局部变量
//必须是final型
//局部方法中的变量可能会消失
System.out.println(x);
}
}
Inner in=new Inner();
in.show();
}
}
class InnerDemo
{
public static void main(String[] args)
{
new Outer().method();
}
}