java 抽象方法的标准可见性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10116029/
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
Standard visibility for abstract methods
提问by Sal
This may seem like a silly question, but I'd like to know the "best practices" when creating abstract methods. Should their visibility be public or protected?
这似乎是一个愚蠢的问题,但我想知道创建抽象方法时的“最佳实践”。他们的可见性应该公开还是受到保护?
Even though a child class implementing the abstract method will be public, is it still advisable to maintain the abstract method protected?
即使实现抽象方法的子类将是公共的,仍然建议保持抽象方法受保护吗?
回答by Jeffrey
Depends on your use case. If the abstract method only implements some piece of a greater functionality that is available from a public method in your abstract class, then it should probably be protected. If it is a standalone method that can/should be called from another class, make it public.
取决于您的用例。如果抽象方法只实现了抽象类中的公共方法可用的一些更大的功能,那么它可能应该受到保护。如果它是可以/应该从另一个类调用的独立方法,请将其设为公开。
Examples:
例子:
public abstract class Foo implements Closeable {
public final void close() {
// do whatever
doClose();
}
protected abstract void doClose();
}
public abstract class Bar {
public void read(byte[] b) {
for(int x = 0; x < b.length; x++) {
b[x] = read();
}
}
public abstract int read();
}
回答by Crazenezz
Here is the difference for public, protected and private:
以下是 public、protected 和 private 的区别:
For method if you set public it can be accessed to all classes within all packages in your project, if you set protected it just can be accessed to all classes within same package or sub class that extend the abstract class.
对于方法,如果您将其设置为 public,则它可以被项目中所有包中的所有类访问,如果您设置为 protected,则它只能被同一包或扩展抽象类的子类中的所有类访问。
For question no. 2: Yes, it is.
对于问题编号。2:是的,是的。
回答by Luciano
I guess it depends on what the method does. If it is something that represents the class (and subclasses) behavior, it should be public. If the method to be implemented by subclasses is internal and used by other methods of the base class (like defining an algorithmic strategy) it should be protected.
我想这取决于方法的作用。如果它是代表类(和子类)行为的东西,它应该是公共的。如果子类要实现的方法是内部的并且被基类的其他方法使用(例如定义算法策略),则应该受到保护。