我知道回答我自己的问题很奇怪,但是......
我想通了。您必须使您的类抽象,并且您可以声明抽象方法以使方法成为“参数”,使其行为类似于 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