我想这样做,但我不能。这是我的情景和理性。我有一个测试用例的抽象类,它有一个名为test()的抽象方法。 test()方法由子类定义;它将使用某个应用程序的逻辑实现,例如CRMAppTestCase extends CompanyTestCase
。我不希望直接调用test()方法,我希望超类调用test()方法,而子类可以调用一个调用它的方法(并做其他工作,例如设置当前例如,在执行测试之前的日期时间。示例代码:
public abstract class CompanyTestCase {
//I wish this would compile, but it cannot be declared private
private abstract void test();
public TestCaseResult performTest() {
//do some work which must be done and should be invoked whenever
//this method is called (it would be improper to expect the caller
// to perform initialization)
TestCaseResult result = new TestCaseResult();
result.setBeginTime(new Date());
long time = System.currentTimeMillis();
test(); //invoke test logic
result.setDuration(System.currentTimeMillis() - time);
return result;
}
}
然后扩展这个......
public class CRMAppTestCase extends CompanyTestCase {
public void test() {
//test logic here
}
}
然后叫它......
TestCaseResult result = new CRMAppTestCase().performTest();
答案 0 :(得分:57)
私有方法不是多态的(你不能继承它们),所以将私有方法抽象是没有意义的。使方法抽象意味着您必须在子类中覆盖和实现它,但由于您不能覆盖私有方法,因此您也不能将它们变为抽象。
您应该protected
而不是private
。
私有真的意味着您已经定义了该方法的类私有;甚至子类也看不到私有方法。
答案 1 :(得分:6)
我想指出的是,选择Java 不要让抽象的私有方法实现(例如在C ++中你可以and is advisable)。说私有方法一般不是多态的,只是不知道调用和定义方法是两种不同的机制 - 虽然子类永远不能调用超类的私有方法,但它们能够定义它。混合这两者是一种常见的误解,请注意。
我没有足够的声誉来评论,这就是我写答案的原因。
答案 2 :(得分:4)
我想这样做,但我不能
更改此项将需要重写编译器,这是不可能的。
你意识到为什么它永远不会起作用,对吧?子类不能覆盖私有方法,但它是抽象的,表示它们必须。第二十二条军规。
答案 3 :(得分:3)
'private'表示该方法只能由类调用。因此必须在类上定义,因此不能是抽象的。如果你想在别处定义方法,你必须使它成为私有的。
答案 4 :(得分:1)
您不能拥有private abstract
方法,因为子类无法看到超类的私有成员。您需要制作test
方法protected
。
答案 5 :(得分:0)
abstract意味着您需要在子类中定义方法
private表示子类不会看到方法
怎么可以编译?
如果该方法最终公开,请将其声明为公共摘要,这就是全部。
答案 6 :(得分:0)
您应该将“测试”方法声明为“受保护”以实现目标。但它仍然可以从课程包中访问。