import java.lang.*;
public class Test {
public static void main(String[] str)
{
Fun(new MyInterface(){public void Say()
{
System.out.println("this is temp interface");
}});
Fun(new People(){public void Say()
{
System.out.println("this is temp class");
}});
}
static void Fun(MyInterface p)
{
p.Say();
}
}
interface MyInterface
{
public void Say();
}
class People implements MyInterface
{
public void Say()
{
System.out.println("this is People");
}
}
程序输出:
this is temp class
第二个例子:
public class Test {
public static void main(String[] str)
{
new Test().TestFun();
}
static void Fun(MyInterface p)
{
p.Say();
}
void Why()
{
System.out.println("Why");
}
void TestFun()
{
Fun(new MyInterface(){public void Say()
{
Test.this.Why();
Why();
//如果加这一句,会进入死循环 this.Say();
//总结,在这个方法里this代表一个MyInterface类型,而可直接使用Test的方法。
}});
}
}
interface MyInterface
{
public void Say();
}
Why
第三个例子
static int Age=123;
public static void main(String[] str) {
Age+=1;
Fun(myInterface);
}
static void Fun(MyInterface p) {
p.Say();
}
static MyInterface myInterface =new MyInterface() {
@Override
public void Say() {
System.out.println(Age);
}
};
}
{
public void Say();
}
程序输出:
123
124
第四个例子:
public static void main(String[] str) {
B.Test();
}
public void Run() {
System.out.println("Test.Run");
}
}
class B {
public static void Test() {
Test t = new Test(){
public void Run() {
System.out.println(this.getClass());
}
};
t.Run();
Test t2=new Test();
System.out.println(t2.getClass());
}
}
class Test
第五个例子:
public static void main(String[] args)
{
A a=new A(){
@Override
void Eat() {
super.Eat();
this.Say();
System.out.println("a.eat");
}
};
a.Eat();
System.out.println((a instanceof A));
System.out.println((a.getClass()));
}
}
class A {
void Say() {
System.out.println("A.Say");
}
void Eat() {
System.out.println("A.Eat");
}
}
程序输出:
A.Say
a.eat
true
class Test$1