-2

In Java, is there a way to have an access modifier which is essentially private, except that this method can be accessed by children? I am developing a program in which there are several methods which are needed by the children of a certain class (and want to avoid duplication), but I don't want to make it public as I do not want the objects these childish classes are instantiated in to have access to these methods.

If there is no such thing, what would you guys recommend as to achieving best practice on this issue?

Preferably in the same package - protected doesn't fulfil this.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Super Hacker
  • 124
  • 2
  • 3
  • 10
  • 1
    https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – frostmatthew Jul 30 '15 at 13:24
  • 3
    Side note: from a "Super Hacker" I would expect some prior research from your end. – GhostCat Jul 30 '15 at 13:36
  • The table in the official tutorial linked above and in the accepted answer is not super pedagogical imo. [Here's a better visualization.](http://stackoverflow.com/a/33627846/276052) – aioobe Nov 13 '15 at 13:18

1 Answers1

8

This is what the protected keyword is for.

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Edit: Please be also aware that the Java Reflection API allows any class to access any member of your classes whatever the modifier.

dotvav
  • 2,808
  • 15
  • 31
  • Is there a keyword which doesn't require separate packages to be effective though? – Super Hacker Jul 30 '15 at 13:26
  • No, such a modifier does not exist. You only can choose between `private`, package access (= no modifier), `protected` (=package access plus extending classes) and `public`. – Florian Schaetz Jul 30 '15 at 13:27
  • @SuperHacker If you mean one that would disable access to classes in the same package that do not extend the type in question, no, there's not. Those classes are written by you; you don't need a keyword to enforce your own policy on yourself. – erickson Jul 30 '15 at 13:29