There is a problem when writing code: an interface class is defined in the package, and another package needs to implement it. Here, the principles of interface isolation and dependency inversion are adopted to invert the dependencies of the two packages. However, we encountered a problem here. The implementation class adopts the factory model to instantiate, so the implementation class does not want to be exposed to the out-of-packet, but the implementation class also needs to implement the public interface. So here is a question: If the class is of default type and the member function is of public type, then what are the access restrictions?
Implement verification
1. First define an interface class in a package:
package mytest public interface ClassAccessTest{ void getData(); CharSeqence getString();}2. Define implementation classes and factories in implementation packages
package classaccesstest import mytest.ClassAccessTest class ClassAccessTestImp implements ClassAccessTest{ int mA = 0; ClassAccessTestImp(int a) { mA = a; } public void getData() { System.out.printlin(" the data is " + mA); } public CharSequence getString() { return (" the data is " + mA); } package classaccesstest import mytest.ClassAccessTest public class Factory{ public static ClassAccessTest getAccessTest() { return new ClassAccessTestImp(10); }}3. Then use the interface in the original package:
package mytest import classcesstest.Factory//import classaccesstest.ClassAccessTestImp public class TestMain{ public static void main(String arg[]) { Factory.getAccessTest().getString();<span style="white-space:pre"> </span>//<span style="font-family: Arial, Helvetica, sans-serif;">ClassAccessTest test = </span>new <span style="font-family: Arial, Helvetica, sans-serif;">ClassAccessTestImp(10);</span> }} 4. Results:
In the TestMain class, the non-commented part can run normally, and the commented part will report an error. ClassAccessTestImp undefined conclusion is derived from the above that the access permissions of classes in Java can be smaller than the access permissions of members. Under the requirements of inversion and package encapsulation, the requirements can be met.