无法声明私有的抽象方法

编程入门 行业动态 更新时间:2024-10-28 03:30:27
本文介绍了无法声明私有的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想这样做,但我做不到。这是我的情景和理性。我有一个测试用例的抽象类,它有一个名为test()的抽象方法。 test()方法由子类定义;它是用某个应用程序的逻辑实现的,例如 CRMAppTestCase扩展CompanyTestCase 。我不希望直接调用test()方法,我希望超类调用test()方法,而子类可以调用一个调用它的方法(并做其他工作,例如设置当前例如,在执行测试之前的日期时间)。示例代码:

I want to do this, yet I can't. Here is my scenario and rational. I have an abstract class for test cases that has an abstract method called test(). The test() method is to be defined by the subclass; it is to be implemented with logic for a certain application, such as CRMAppTestCase extends CompanyTestCase. I don't want the test() method to be invoked directly, I want the super class to call the test() method while the sub class can call a method which calls this (and does other work too, such as setting a current date-time right before the test is executed for example). Example code:

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; } }

然后扩展这个....

Then to extend this....

public class CRMAppTestCase extends CompanyTestCase { public void test() { //test logic here } }

然后调用它... 。

TestCaseResult result = new CRMAppTestCase().performTest();

推荐答案

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

Private methods are not polymorphic (you cannot inherit them), so it makes no sense to make a private method abstract. Making a method abstract means you'd have to override and implement it in a subclass, but since you can't override private methods, you can't make them abstract either.

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

You should make it protected instead of private.

Private确实意味着您已经定义了该方法的类的私有;甚至子类也看不到私有方法。

Private really means private to the class you've defined the method in; even subclasses don't see private methods.

更多推荐

无法声明私有的抽象方法

本文发布于:2023-11-16 10:18:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抽象   声明   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!