/*
内部类的访问规则:
1,内部类可以直接访问外部类中的成员,包括私有。
内部类之所以可以直接访问外部类中的成员,是因为内
部类中持有了一个外部类的引用。格式:外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,可以在
外部其他类中。可以直接建立内部类对象。
格式:外部类名.内部类名 变量名 = new 外部类名().new 内部类名();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private: 将内部类在外部类中进行封装。
static:内部类就具备了静态的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。
在外部其他类中,如何直接访问静态内部类呢?
*/
class Outer
{
private int x = 3;
/*
private class Inner //内部类,且内部类在外部类的成员位置上时,可以被private修饰
{
int x = 4;
void function()
{
int x = 6;
System.out.println("inner :"+this.x);//输出4
System.out.println("inner :"+Outer.this.x); //输出3
}
}
*/
static class Inner
{
void function()
{
System.out.println("inner :"+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,内部类可以直接访问外部类中的成员,包括私有。
内部类之所以可以直接访问外部类中的成员,是因为内
部类中持有了一个外部类的引用。格式:外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,可以在
外部其他类中。可以直接建立内部类对象。
格式:外部类名.内部类名 变量名 = new 外部类名().new 内部类名();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private: 将内部类在外部类中进行封装。
static:内部类就具备了静态的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。
在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员呢?
Outer.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的
当外部类中的静态方法访问内部类时,内部类也必须是静态的。
当描述事物时,事物的内部还有事物,该事物用内部类来描述。
因为内部事物在使用外部事物的内容
class Body
{
private class XinZhang
{
}
public void show()
{
new XinZhang()
}
}
*/
class Outer
{
private static int x = 3;
static class Inner
{
static void function() //静态内部类的静态方法
{
System.out.println("inner :"+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.Inner.function();//外部类访问静态内部类的静态方法
// new Outer.Inner().function();
}
}
--------------------------------------------------------------------------------------------------------------
/*
内部类定义在局部时:
1,不可以被成员修饰符修饰
2,可以直接访问外部类中的成员,因为还持有外部类中的引用。
但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
*/
class Outer
{
int x = 3;
void method(final int a)
{
final int y = 4;
class Inner //内部定义在局部位置,访问时要创建对象
{
void function()
{
System.out.println(a);
System.out.println(y);
System.out.println(Outer.this.x);
}
}
new Inner().function();//创建内部类对象
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
//new Outer().method();
Outer out = new Outer();
out.method(7);//输出7 注意区别!!!!!!!!!!
out.method(8);//输出8
}
}
------------------------------------------------------------------------------------------------------------------
个人总结:掌握创建内部类对象,注意各种访问方法,注意内部类定义在局部时的方法
方式。