/***********************************
* 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内部类??
* 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内部类??
protected等只是访问权限修饰词,只是给类定的作用范围
这时,你把SimpleClass中的子类Inner的可见性改为public,那么,就可以通过编译。所以,把内部类声明为protected,可以提高封装性能。package c08.exercise12b;import c08.exercise12.*;public class AnotherPackageClass {
public void f() {
SimpleClass sc = new SimpleClass();
sc.new Inner().f();
}
}