第一個例子:
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 interface
this is temp class
第二個例子:
import java.lang.*;
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
Why
第三個例子
public class Test {
static int Age=123;
public static void main(String[] str) {
System.out.println(myInterface.getClass());
Fun(myInterface);
Age+=1;
Fun(myInterface);
}
static void Fun(MyInterface p) {
p.Say();
}
static MyInterface myInterface =new MyInterface() {
@Override
public void Say() {
System.out.println(Age);
}
};
}
interface MyInterface
{
public void Say();
}
程式輸出:
class Test$1
123
124
第四個例子:
public class Test {
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 B$1
class Test
第五個例子:
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.Eat
A.Say
a.eat
true
class Test$1