1

"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?

Sarthak Mittal
  • 135
  • 1
  • 2
  • 11

1 Answers1

3

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
Tim Hunter
  • 826
  • 5
  • 10
  • So outside class can use the InfiltratorClass infiltrator method to get access of the package-private visibility variables. Am i getting it right? Here we can make a InfiltratorClass but when we are using a external library. Then we cannot create the InfiltratorClass so the encapsulation can not be broken in that case? – Sarthak Mittal Jul 20 '21 at 13:45
  • 1
    @SarthakMittal Yep, you can make `InfiltratorClass` directly edit the value with a `setVar1()` method for example. Using an external library [isn't impervious to tampering](https://www.infoworld.com/article/2072723/hacking-java-libraries.html), but proper usage of the `private` keyword can prevent `InfiltratorClass` from accessing the variable in general usage cases. – Tim Hunter Jul 20 '21 at 13:59