我知道这是怪异回答我的问题,但...
我想通了。您必须使您的类变为抽象类型,并且您可以声明抽象方法来使方法“参数”具有类似于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 –