内部类访问规则
class Outer
{
private int x = 3 ;
class Inner //内部类
{
void function ()
{
System.out.println("innner :" +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();
}
}
静态内部类
/*
内部类的访问规则:
1 ,内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
2 ,外部类要访问内部类,必须建立内部类对象。
访问格式:
1 ,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。
可以直接建立内部类对象。
格式
外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer().new Inner();
2 ,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private :将内部类在外部类中进行封装。
static :内部类就具备static 的特性。
当内部类被static 修饰后,只能直接访问外部类中的static 成员。出现了访问局限。
在外部其他类中,如何直接访问static 内部类的非静态成员呢?
new Outer.Inner().function ();
在外部其他类中,如何直接访问static 内部类的静态成员呢?
uter.Inner.function ();
注意:当内部类中定义了静态成员,该内部类必须是static 的。
当外部类中的静态方法访问内部类时,内部类也必须是static 的。
当描述事物时,事物的内部还有事物,该事物用内部类来描述。
因为内部事务在使用外部事物的内容。
class Body
{
private class XinZang
{
}
public void show()
{
new XinZang().
}
}
*/
class Outer
{
private static int x = 3 ;
static class Inner
{
static void function ()
{
System.out.println("innner :" +x);
}
}
static class Inner2
{
void show()
{
System.out.println("inner2 show" );
}
}
public static void method()
{
new Inner2().show();
}
}
class InnerClassDemo2
{
public static void main(String[] args)
{
Outer.method();
}
}
匿名内部类
/*
匿名内部类:
1 ,匿名内部类其实就是内部类的简写格式。
2 ,定义匿名内部类的前提:
内部类必须是继承一个类或者实现接口。
3 ,匿名内部类的格式: new 父类或者接口(){定义子类的内容}
4 ,其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。 可以理解为带内容的对象。
5 ,匿名内部类中定义的方法最好不要超过3 个。
*/
abstract class AbsDemo
{
abstract void show();
}
class Outer
{
int x = 3 ;
/*
class Inner extends AbsDemo
{
int num = 90 ;
void show()
{
System.out.println("show :" +num);
}
void abc()
{
System.out.println("hehe" );
}
}
*/
public void function ()
{
// AbsDemo a = new Inner();
// Inner in = new Inner();
// in .show();
// in .abc();
AbsDemo d = new AbsDemo()
{
int num = 9 ;
void show()
{
System.out.println("num===" +num);
}
void abc()
{
System.out.println("haha" );
}
};
d.show();
// d.abc();// 编译失败;
}
}
class InnerClassDemo4
{
public static void main(String[] args)
{
new Outer().function ();
}
}
小练习
interface Inter
{
void method();
}
class Test
{
static Inter function ()
{
return new Inter()
{
public void method()
{
System.out.println("method run" );
}
};
}
}
class InnerClassTest
{
public static void main(String[] args)
{
Test.function ().method();
}
}