Pros and cons of package private classes in Java?

前端 未结 8 1822
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 05:05

I am learning Java recently, and I came across the notion of package-private classes, which is the default if we don\'t specify anything. But then I realized:

8条回答
  •  不知归路
    2020-11-27 05:17

    The package-private access level is more restrictive than protected: protected attributes and methods can still be accessed by simply subclassing a class. Protected members are (or may be) intended for inheritance while package-private members are not.

    Package-private members are often used so multilpe classes inside a package can access implementation-specific attributes or (utility) methods.

    Good examples to this are the package-private constructor of String and the StringBuilder.value char array:

    /*
    * Package private constructor which shares value array for speed.
    * this constructor is always expected to be called with share==true.
    * a separate constructor is needed because we already have a public
    * String(char[]) constructor that makes a copy of the given char[].
    */
    String(char[] value, boolean share) {
        // assert share : "unshared not supported";
        this.value = value;
    }
    

    So classes inside the java.lang package can efficiently create new Strings if the content is already present in a char[] without compromising security. You cannot do this from your application because if you could, you would have access (reference) to the internal char array of a String which is immutable (reflection not counted!).

    In StringBuilder (or rather AbstractStringBuilder where the implementation comes from) the char array holding the current value char[] value and an accessor method to this char[] getValue() are also package-private so various utility methods of String like contentEquals(StringBuffer sb) and contentEquals(CharSequence cs) can utilize this for efficiency and faster comparisons without exposing the internal char array to the "world".

提交回复
热议问题