How can be encapsulation broken in package-private declarations in Java

246 Views Asked by At

"The encapsulation can be easily broken, because external code can define classes in the same packages used by your code and thus get access to your package-private declarations."

I am not able to understand how can we achieve what is written in the statement. How can encapsulation be broken?

1

There are 1 best solutions below

2
Tim Hunter On

You can see what this means with a small example.

Here we have a class with some package-private visibility variables, the visibility applied when not using a visibility keyword.

package insider;

public class PrivateClass {
  static int var1 = 10;
  static String var2 = "Secret";
}

Here I have a class in another package. This will throw none visibility errors for the variables.

package outsider;

import insider.PrivateClass;

public class OutsiderClass {
  public static void outsider() {
    System.out.println(PrivateClass.var2 + " " + PrivateClass.var1);
  }
}

Here I have a class in the same package as our package-private variables class. This one does not throw an error when accessing the variables.

package insider;

public class InfiltratorClass {
  public static void infiltrator() {
    System.out.println(PrivateClass.var2 + " " + PrivateClass.var1);
  }
}

File Structure Overview:

insider
  PrivateClass
  InfiltratorClass
outsider
  OutsiderClass