class out
{
private int index = 100;
class in
{
private int index = 50;
void print()
{
int index = 30;
System.out.println(index); //30,print访问的是局部变量
System.out.println(this.index); //50
System.out.println(out.this.index); //100
}
}
in getIn()
{
return new in();
}
}
class init
{
public static void main(String[] args)
{
out o = new out();
// o.in i = out.getIn();
// i.print();
o.in i = o.new in(); //内部类要访问外部类,那么必须有关联性,不能直接new
}
}
当在方法中定义一个类,那么如果类要访问方法的变量,那么这个变量必须为final。内部类的修饰符public,protected,private,abstract,static, 非静态的内部类不能有静态方法,只有顶层类才可以有static成员
内部类实现接口,更好的管理类
interfice Animal
{
void eat();
void sleep();
}
class Zoo
{
private class Tiger implements Animal
{
public void eat
{
System.put.println("tiger eat");
}
public void sleep()
{
System.put.println("tiger sleep");
}
}
Animal getAnimal()
{
return new Tiger();
}
}
class Test
{
public static void main(String[] args)
{
Zoo z = new Zoo();
Animal an = z.getAnimal();
an.eat(); //利用内部类的接口访问私有成员
an.sleep();
}
}
内部类和接口的函数名相同,但意义不一样
interface Machine
{
void run();
}
class Person
{
void run()
{
System.out.println("person run");
}
}
class Robot extends Person
{
private class MachineHeart implements Machine
{
public void run()
{
System.out.println("robot heart");
}
}
Machine getMachine()
{
return new MachineHerat();
}
}
class Test
{
public void main(String[] args)
{
Robot robot = new Robot();
Machine m = robot.getMachine();
m.run();
robot.run();
}
}
内部类解决c++中多继承问题
class A
{
void f1();
}
abstract B
{
abstract void f2();
}
class C extends A
{
B getB()
{
return new B() //返回一个内置类
{
public void f2()
{}
};
}
}
class Test
{
static void m1(A a)
{
a.f1();
}
static void m2(B b)
{
b.f2();
}
public static void main(String[] args)
{
C c = new C();
m1(c);
m2(c.getB());
}
}