/*
内部类定义在局部
01 不可以被成员修饰符修饰
02 可以直接访问外部类的成员 因为还持有外部类的引用
但是不可以访问他所在的局部中的变量 只能访问被fianl修饰的局部变量
class Outer
{
int x=3;
void show(final int a)
{
final int y=123;
class Inter
{
void funtion()
{
// 可以直接访问外部类的成员 因为还持有外部类的引用
System.out.println(Outer.this.x);
// 无法访问 但是加上final就可以访问
System.out.println(y);
System.out.println(a);
}
}
//这个是匿名对象 通过匿名对象访问内部类
new Inter().funtion();
}
}
class Inter
{
public static void main(String[] args)
{
//new Outer().show();
Outer out=new Outer();
// out.show(7);
out.show(90);
}
}
*/
/*
匿名内部类
1 就是内部类的简写格式
2 定义匿名内部类的前提是 内部类必须继承一个类 或者是实现一个接口
3 内部类可以继承外部其他抽象类 和接口
4 匿名内部类 格式 new 父类或者接口(){定义的子类内容}
5 匿名内部类是一个匿名子类对象
6 匿名内部类中的方法最好不要超过3个
*/
abstract class Demo
{
abstract void method();
}
class Outer
{
//int x=22;
/*class Inter extends Demo
{
//int x=12121;
void method()
{
//System.out.println(Outer.this.x);
System.out.println(x);
}
}
*/
public void funtion()
{
/*
//匿名内部类
new Demo()
{
void method()
{
System.out.println("#23");
}
void show()
{
System.out.println("21");
}
}.show();
new Demo()
{
void method()
{
System.out.println("#23");
}
void show()
{
System.out.println("21");
}
}.method();
Demo d=new Demo()
{
void method()
{
System.out.println("1");
}
void show()
{
System.out.println("12314");
}
};
d.show();
d.method();
*/
Demo dd=new Demo()
{
void show()
{
System.out.println("21");
}
void method()
{
System.out.println("#23");
}
};
dd.method();
// 编译失败
// dd.show();
}
}
class Inter
{
public static void main(String[] args)
{
//Outer out=new Outer();
//out.funtion();
new Outer().funtion();
}
}
//匿名内部类
interface Inter
{
void show();
}
class Demo
{
/* 01 定义一个静态内部类
static class Imnter1 implements Inter
{
public void show()
{
System.out.println("12");
}
}
// 用于访问内部类
static Imnter1 funtion()
{
return new Imnter1();
}
//02 用匿名对象访问 内部类
static Inter funtion()
{
return new Inter
}
*/
}
class Innter
{
public static void main(String[] args)
{
// Demo.funtion().show();
show(new Inter()
{
public void show()
{
System.out.println("121");
}
});
}
public static void show(Inter in)
{
in.show();
}
}
//面试题 匿名内部类 内部类必须是继承一个类或者是实现一个接口
class Inntertest
{
public static void main(String[] arg)
{
new Object()
{
public void funtion()
{
}
}.funtion();
}
}
详细请查看:<a href="http://edu.csdn.net" target="blank">http://edu.csdn.net</a>