gpt4 book ai didi

java - 无法将抽象方法声明为私有(private)

转载 作者:太空狗 更新时间:2023-10-29 22:41:51 26 4
gpt4 key购买 nike

我想做,但我做不到。这是我的情景和理性。我有一个用于测试用例的抽象类,它有一个名为 test() 的抽象方法。 test() 方法由子类定义;它是针对某个应用程序用逻辑来实现的,例如CRMAppTestCase extends CompanyTestCase。我不希望直接调用 test() 方法,我希望父类(super class)调用 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();

最佳答案

私有(private)方法不是多态的(你不能继承它们),所以将私有(private)方法抽象化是没有意义的。使方法抽象意味着您必须在子类中覆盖和实现它,但由于您不能覆盖私有(private)方法,因此您也不能使它们抽象。

您应该将其设置为 protected 而不是 private

Private 的真正含义是对您在其中定义该方法的类私有(private);甚至子类也看不到私有(private)方法。

关于java - 无法将抽象方法声明为私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com