Explain : Anonymous Class 是為一種方便建立繼承的方法, 也可用在介面上, 它會將名稱隱藏起來 形成 class X Y(IS-A class or implements class), 不用寫 X, 只要 Y ok
其型式為:
X = new Y() {
method....
}
Simple code: AnyClassTest.java
{{{
public class AnyClassTest{
public static void main(String[] args){
//Thread t = new Thread(new TestRun());
//t.start();
Thread t = new Thread(new Runnable(){ // implement runnable
public void run(){
System.out.println("haha");
}
});
t.start();
Point p = new Point(){ // extend point
public void sayHa(){
System.out.println("hahahaha");
}
};
p.sayHa();
}
/*
static class TestRun implements Runnable{
public void run(){
System.out.println("haha");
}
}*/
static class Point {
public void sayHa(){
System.out.println("ha");
}
}
}
}}}
Output:
{{{
[Andy@t-ap188 row]$ java AnyClassTest
hahahaha
haha
}}}
沒有留言:
張貼留言