0

There is a project named demo which consists of two packages, named aa and bb.

In package aa I have a public class One which has a method with protected as a modifier.

Now in the other package bb , I have a public class two which wants to access the package aa class One protected method.

Please advise how that will be done..!

user1582269
  • 285
  • 1
  • 6
  • 12

4 Answers4

3

protected methods are visible only in the same class, class from same package, and class extending it

jmj
  • 237,923
  • 42
  • 401
  • 438
3

You can not access protected members/methods from class in another package until you inherit it.

You have following options :

  1. public Class Two extends One
  2. Add Classes One and Two in same package.
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
1

Protected methods are visible only in derived classes, or classes in the same package.
Since the protected method is in a different class, you have two options:

  1. Change the access specifier to public
  2. Derive the using class from the class with the protected specifier: class Two extends One

There is a third option, which is to reproduce the protected method in class Two. This is not recommended, and is not always possible - for example if the method handles members that are private to class One.

0

What Jigar and S.L Barth say is right, i.e., it's only accessible from the derived classes or classes in the same package.

For more information, the official Java documentation spells out the accessibility and visibility of methods quite clearly.

Controlling Access to Members of a Class

andyroberts
  • 3,458
  • 2
  • 37
  • 40