user1582269
user1582269

Reputation: 305

Regarding accessing the protected method

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..!

Upvotes: 0

Views: 153

Answers (4)

andyroberts
andyroberts

Reputation: 3518

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

Upvotes: 0

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.

Upvotes: 1

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

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.

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240966

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

Upvotes: 3

Related Questions