有人可以向我解释一下protected
/ public
内部课程有什么区别?
我知道public
内部类是尽可能避免的(就像在这个article中解释的那样)。
但据我所知,使用protected
或public
修饰符没有区别。
看看这个例子:
public class Foo1 {
public Foo1() { }
protected class InnerFoo {
public InnerFoo() {
super();
}
}
}
...
public class Foo2 extends Foo1 {
public Foo2() {
Foo1.InnerFoo innerFoo = new Foo1.InnerFoo();
}
}
...
public class Bar {
public Bar() {
Foo1 foo1 = new Foo1();
Foo1.InnerFoo innerFoo1 = foo1.new InnerFoo();
Foo2 foo2 = new Foo2();
Foo2.InnerFoo innerFoo2 = foo2.new InnerFoo();
}
}
所有这些都编译并且无论我是宣布InnerFoo
protected
还是public
都是有效的。
我错过了什么?请指出一个使用protected
或public
有区别的情况。
谢谢。
protected
访问修饰符将限制来自同一包及其子类中的类以外的类的访问。
在所示的示例中,public
和protected
将具有相同的效果,因为它们在同一个包中。
有关访问修饰符的更多信息,Controlling Access to Members of a Class的The Java Tutorials页面可能会引起关注。
您可以认为受保护的内部类是受保护的成员,因此它只能访问类,包,子类而不能访问世界。
另外,对于外类,只有两个访问修饰符。只是公开和包装。
纯Java:您无法从公共getter返回私有内部类。
在JSP中:您不能从公共getter返回非公共内部类。
您可以运行的Java演示:
public class ReturnInnerClass{
public static void main(String []args){
MyClass inst = new MyClass("[PROP_VAL]");
System.out.println(
inst.get().myProperty()
);;
};;
};;
class MyClass{
//:If JSP: MUST be public
//:Pure Java:
//: public,protected,no-access-modifier
//: Will all work.
//:Private fails in both pure java & jsp.
protected class Getters{
public String
myProperty(){ return(my_property); }
};;
//:JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
//:How to run this example:
//: 1: Put this code in file called: "ReturnInnerClass.java"
//: 2: Put ReturnInnerClass.java into it's own folder.
//: ( Folder name does not matter.)
//: 3: Open the folder.
//: 4: Right-Click --> GitBashHere
//: 5: In command prompt within folder:
//: 5.1: javac ReturnInnerClass.java
//: 5.2: java ReturnInnerClass
//: ( javac: java compiler )
//: ( java : runs compiled java program )
//: EXPECTED OUTPUT:
//: [PROP_VAL]
对于JSP,只将上面的类代码放到文件夹:com / myPackage / MyClass中,并将“import com.myPackage.MyClass”作为第一行源代码。然后使用以下源代码创建一个新的.jsp页面:
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
使用的堆栈:Java8 + Tomcat9