内部类的相关内容:
/*
内部类访问特点:
1,内部类可以直接访问外部类中的成员。
2,外部类要访问内部类,必须建立内部类的对象
用于类的设计:
分析事物时,发现该事物描述中还有事物,而且这个事物还在访问被描述事物的内容,
这时就是还有的事物定义成内部类来描述。
*/
class Outer
{
private int num = 3;
class Inner//内部类
{
int num = 4;
void show()
{
int num = 5;
System.out.println("show run...."+ num);//num = 5
System.out.println(this.num);//num = 4
System.out.println(Outer.this.num);//num = 3
}
/*
static void function()//如果内部类定义了静态成员,该内部类也必须是静态的。
{
System.out.println("function run....");
}
*/
}
public void method()
{
Inner in = new Inner();
in.show();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
//Outer out = new Outer();
//out.method();
Outer.Inner in = new Outer().new Inner();//直接访问外部类中的内部类的成员
in.show();
//如果内部类是静态的,成员是静态的
//Outer.Inner.function();
}
}
内部类--局部类
/*
内部类可以存放在局部位置上。
内部类在局部位置上只能访问局部中被final修饰的局部变量。
*/
class Outer
{
int num = 3;
void method()
{
final int x = 3;
class Inner
{
void show()
{
System.out.println("show..." + x);
}
}
Inner in = new Inner();
in.show();
}
}
class InnerClassDemo2
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method();
}
}
匿名内部类:
/*
匿名内部类,就是内部类的简写格式。
必须有前提:
内部类必须继承或者实现一个外部类或者接口。
通常的使用场景:
当函数参数是接口类型时,而且接口中的方法不超过三个,
,可以使用匿名内部类作为实际参数进行传递。
*/
interface Inter
{
void show1();
void show2();
}
abstract class demo
{
abstract void show();
}
class Outer
{
int num = 4;
public void method()
{
new demo()//匿名内部类,继承demo父类
{
void show()
{
System.out.println("show..."+num);
}
}.show();//调用子类方法
Inter in = new Inter()//因为匿名内部类这个子类对象被向上转型为了Inter类型
{ //这样就不能再使用子类特有的方法 show3()了。
public void show1()
{
System.out.println("show1...");
}
public void show2()
{
System.out.println("show2...");
}
/*
public void show3()
{
System.out.println("show3...");
}
*/
};
in.show1();
in.show2();
//in.show3();
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
new Outer().method();
}