java 公共与受保护的抽象类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34260507/
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
Public vs. Protected abstract class method
提问by Region39
Is there any security/access difference when making a package access level abstract class's non-static methods public vs making them protected? Only classes from within the same package that extend the abstract class can access the non-static methods anyway right? So, does it matter whether those non-static methods are public or protected since the abstract class itself places restrictions on who can extend it?
将包访问级别抽象类的非静态方法设为公开与将它们保护起来时,是否有任何安全/访问差异?只有来自同一包中的扩展抽象类的类才能访问非静态方法,对吗?那么,这些非静态方法是公共的还是受保护的,因为抽象类本身对谁可以扩展它施加了限制,这是否重要?
abstract class MyClass {
protected void myFunction(){
System.out.println("Only child classes can print this");
}
}
abstract class MyClass {
public void myFunction(){
System.out.println("Still, only child classes can print this");
}
}
回答by YoungHobbit
The public abstract method
will be accessible in the other package where as the protected abstract method
can not be accessed. Check the example below.
该public abstract method
会是在为其他包访问protected abstract method
不能被访问。检查下面的示例。
An abstract class with both public and protected abstract methods
具有公共和受保护抽象方法的抽象类
package package1;
public abstract class MyClass {
abstract protected String method1();
abstract public String method2();
}
Another package which extends the class and implements the abstract class.
另一个扩展类并实现抽象类的包。
package package2;
import package1.MyClass;
public class MyClassImpl extends MyClass {
@Override
protected String method1() {
return "protected method";
}
@Override
public String method2() {
return "public method";
}
}
Main class for accessing the abstract method.
用于访问抽象方法的主类。
package package2;
import package1.MyClass;
public class MainClass {
static MyClass myClass = new MyClassImpl();
public static void main(String[] args) {
System.out.println(myClass.method1()); // This is compilation error.
System.out.println(myClass.method2());
}
}