java class access rights and member access rights resolution


There is a problem when writing code: the package defines an interface class and the other package implements it. Here, the interface isolation and dependency inversion principle is used to invert the dependencies of the two packages. However, there is a problem with the implementation class being instantiated in factory mode, so the implementation class doesn’t want to be exposed outside of the package, but the implementation class also has to implement the public interface. So there’s a question here, if the class is of type default and the member function is of type public, what are the access restrictions ? Implementation validation 1. Define an interface class in a package:

package mytest

public interface ClassAccessTest
{
  void getData();
  CharSeqence getString();
}

2. Define the implementation class and factory

in the implementation package

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 ClasAccessTest getAccessTest()
  {
    return new ClassAccessTestImp(10);
  }
}

3. Use the interface again in the original package:

package mytest

import classacesstest.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 parts that are not commented out work fine, the parts that are commented out report an error, and ClassAccessTestImp does not define Conclusion From the above, it can be inferred that the access permission of the class in java can be less than that of the member, and the requirements of inversion and package encapsulation can be met.