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
Java: how to implement private abstract methods?
提问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 abstract
methods 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 abstract
method.
如果您想要类似的行为,则需要protected abstract
方法。
It is a compile-time error if a method declaration that contains the keyword
abstract
also contains any one of the keywordsprivate
,static
,final
,native
,strictfp
, orsynchronized
.
如果包含关键字的方法声明
abstract
也包含关键字private
,static
,final
,native
,strictfp
, or中的任何一个,则会出现编译时错误synchronized
。
And
和
It would be impossible for a subclass to implement a
private abstract
method, becauseprivate
methods are not inherited by subclasses; therefore such a method could never be used.
子类不可能实现一个
private abstract
方法,因为private
方法不是由子类继承的;因此这种方法永远无法使用。
Resources :
资源 :
回答by Roland Illig
That would be protected
instead of private
. It means that only classes that extend MyCommand
have access to the two methods. (So do all classes from the same package, but that's a minor point.)
那将protected
代替private
. 这意味着只有扩展的类MyCommand
才能访问这两个方法。(所有类都来自同一个包,但这是一个小问题。)