2

If class B extends A, then public and protected variables of A are inherited by B, and private variables are not. But public and protected variables are directly accessible by other classes of the same package.

How can I make these inherited variables private?

anonymous
  • 448
  • 1
  • 6
  • 25
  • 2
    Possible duplicate of [Why is there no sub-class visibility modifier in Java?](https://stackoverflow.com/questions/5300163/why-is-there-no-sub-class-visibility-modifier-in-java) – DPM Sep 03 '17 at 08:24
  • if you want to go crazy, use a custom annotation and a custom rule in a static code analyzer, then use it with your build tool and fail your build whenever there's a package-but-not-subclass method call of such an annotated method. – DPM Sep 03 '17 at 12:08

2 Answers2

4

You can't. Java's access modifiers are not expressive enough for that.

The only way you can prevent access from other classes in the same package is to make it vacuously true: have no other classes in the same package.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I am really having difficulty understanding. First according to Java's way, you should have all your fields private. But then, if you want to inherit a field, it should not be private. Then how will I make inherited fields private? Why am I not allowed to? – anonymous Sep 03 '17 at 08:50
0

Not sure if it fits here because there are not enough details but if want to give access only to specific methods you can create an Interface that exposes what you want and have the classes you talked about implement it.

Tal Joffe
  • 5,347
  • 4
  • 25
  • 31