/***********************************
 * Create an interface with at least one method,
 * in its own package. Create a class in a
 * separate package. Add a protected inner class
 * that implements the interface. In a third
 * package, inherit from your class and, inside a
 * method, return an object of the protected
 * inner class, upcasting to the interface during
 * the return.
 ***********************************************/
import c08.exercise12b.*;
import c08.exercise12.*;
public class E12_ProtectedInnerClass
extends SimpleClass {
  public SimpleInterface get() {
    return new Inner();
  }
  public static void main(String args[]) {
    new E12_ProtectedInnerClass().get().f();
  }
} ///:~//: c08:exercise12:SimpleInterface.java
package c08.exercise12;
public interface SimpleInterface {
  void f();
} ///:~//: c08:exercise12b:SimpleClass.java
package c08.exercise12b;
import c08.exercise12.*;
public class SimpleClass {
  protected class Inner 
  implements SimpleInterface {
    // Force constructor to be public:
    public Inner() {}
    public void f() {}
  }
} ///:~内部类是protected,为什么不写public的Inner(),使用默认构造器,外部的包就无法访问Inner内部类??

解决方案 »

  1.   

    protected 的作用范围可以达到被不同包中的子类调用;而public 可以被所有的类访问啊,你要使用public 不是扩大范围吗?
    protected等只是访问权限修饰词,只是给类定的作用范围
      

  2.   

    保持你当前的代码不变。另外创建一个类,代码如下。你会发现不能编译通过。
    这时,你把SimpleClass中的子类Inner的可见性改为public,那么,就可以通过编译。所以,把内部类声明为protected,可以提高封装性能。package c08.exercise12b;import c08.exercise12.*;public class AnotherPackageClass {
        public void f() {
            SimpleClass sc = new SimpleClass();
            sc.new Inner().f();
        }
    }
      

  3.   

    可能我说的不是很清楚在inner class中定义了public Inner(){}构造器。但如果我不定义这个构造器,而使用系统默认的构造器,编译就会出错。。这时什么原因???
      

  4.   

    你说得确实不清楚,并且不是一般的不清楚。那个空的构造器的实际作用就是声明了其可见度,因为inner Class默认的构造函数不是public。