【发布时间】:2012-12-30 17:57:49
【问题描述】:
我找不到一个好的总结来描述我的问题(欢迎提出建议)
我有以下两个课程:
测试1
import java.lang.reflect.Method;
abstract class Test1 {
boolean condition = true;
public void f() {
System.out.println("Test1 : f");
}
public void g() {
System.out.println("Test1 : g");
f();
if (condition) {
f(); // call Test1.f() here. HOW?
// Following didn't work
try {
Method m = Test1.class.getDeclaredMethod("f");
m.invoke(this);
} catch (Exception e) {
System.err.println(e);
}
}
}
}
测试2
class Test2 extends Test1 {
public void f() {
System.out.println("Test2 : f ");
}
public static void main(String[] args) {
Test2 t2 = new Test2();
t2.g();
}
}
输出是:
Test1 : g
Test2 : f
Test2 : f
Test2 : f
问题是由于Test1中的condition字段给出的一些特殊条件,我想在g()中调用Test1的f(),即使我使用Test2的对象进行调用.
我尝试了反射,但它也不起作用。有什么建议吗?
编辑 1: 我没有具体提到它,但如果你仔细看Test1是抽象的。所以我不能创建它的对象。
【问题讨论】:
标签: java inheritance overriding subclass superclass