我知道這是怪異回答我的問題,但...
我想通了。您必須使您的類變爲抽象類型,並且您可以聲明抽象方法來使方法「參數」具有類似於KeyListener聲明的行爲。抽象方法聲明如下:
abstract ReturnType name(Parameter p);
並且在調用時的行爲與方法完全相同。舉一個完整的例子:
//The abstract keyword enables abstract methods to work with this class.
abstract class Foo {
//Just a random variable and a constructor to initialize it
int blah;
public Foo(int blah) {
this.blah = blah;
}
//An abstract method
abstract void doStuff();
//Example with a parameter
abstract void whatDoIDoWith(int thisNumber);
//A normal method that will call these methods.
public void doThings() {
//Call our abstract method.
doStuff();
//Call whatDoIDoWith() and give it the parameter 5, because, well... 5!
whatDoIDoWith(5);
}
}
當你試圖實例化一個像普通類的抽象類時,Java會嚇壞了。
Foo f = new Foo(4);
你將需要做的就是這樣的事情:你需要包括所有的抽象方法在這裏
Foo f = new Foo(4) {
@Override
void doStuff() {
System.out.println("Hi guys! I am an abstract method!");
}
@Override
void whatDoIDoWith(int thisNumber) {
blah += thisNumber;
System.out.println(blah);
}
}; //Always remember this semicolon!
注意,不只是其中的一部分。現在,讓我們試試這個:
public class Main {
public static void main(String[] args) {
//Instance foo.
Foo f = new Foo(4) {
@Override
void doStuff() {
System.out.println("Hi guys! I am an abstract method!");
}
@Override
void whatDoIDoWith(int thisNumber) {
blah += thisNumber;
System.out.println(blah);
}
};
//Call our method where we called our two abstract methods.
foo.doThings();
}
}
這將打印以下控制檯:
Hi guys! I am an abstract method!
9
看看這個,http://stackoverflow.com/questions/4685563/how-to-pass -a-功能作爲一種參數中的Java –