Java:如何实现私有抽象方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3851747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:50:01  来源:igfitidea点击:

Java: how to implement private abstract methods?

java

提问by elsni

Is it possible to define a private abstract class in Java? How would a Java developer write a construct like below?

是否可以在 Java 中定义私有抽象类?Java 开发人员将如何编写如下所示的构造?

public abstract class MyCommand {
    public void execute()
    {
        if (areRequirementsFulfilled())
        {
            executeInternal();
        }
    }
    private abstract void executeInternal();
    private abstract boolean areRequirementsFulfilled();
}

采纳答案by Colin Hebert

You can't have private abstractmethods in Java.

private abstract在 Java 中不能有方法。

When a method is private, the sub classes can't access it, hence they can't override it.

当一个方法是 时private,子类不能访问它,因此它们不能覆盖它。

If you want a similar behavior you'll need protected abstractmethod.

如果您想要类似的行为,则需要protected abstract方法。

It is a compile-time error if a method declaration that contains the keyword abstractalso contains any one of the keywords private, static, final, native, strictfp, or synchronized.

如果包含关键字的方法声明abstract也包含关键字private, static, final, native, strictfp, or中的任何一个,则会出现编译时错误synchronized

And

It would be impossible for a subclass to implement a private abstractmethod, because privatemethods are not inherited by subclasses; therefore such a method could never be used.

子类不可能实现一个private abstract方法,因为private方法不是由子类继承的;因此这种方法永远无法使用。



Resources :

资源 :

回答by Roland Illig

That would be protectedinstead of private. It means that only classes that extend MyCommandhave access to the two methods. (So do all classes from the same package, but that's a minor point.)

那将protected代替private. 这意味着只有扩展的类MyCommand才能访问这两个方法。(所有类都来自同一个包,但这是一个小问题。)