受保护/公共内部类

有人可以向我解释一下protected / public 内部课程之间的区别是什么?

我知道public内部课程应尽可能避免(如本文所述 )。

但据我所知,使用protectedpublic修饰符之间没有区别。

看看这个例子:

 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 protectedpublic

我错过了什么? 请指出我在使用protectedpublic存在差异的情况。

谢谢。

protected访问修饰符将限制来自同一包及其子类中的类以外的类的访问。

在所示的示例中, publicprotected将具有相同的效果,因为它们位于同一个包中。

有关访问修饰符的更多信息,可能会对“Java教程”的“ 控制对类成员的访问”页面感兴趣。

你可以认为受保护的内部类是受保护的成员,因此它只能访问类,包,子类,但不能访问世界。

另外,对于outter类,它只有两个访问修饰符。 只是公开和包装。

java中的奇怪之处:

纯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 ); %> ${ my_inst.get().myProperty() }  

使用的堆栈: Java8 + Tomcat9