I have a library project with two packages say package1 and package2 with class1 and class2 respectively. class1 has some public methods exposed to end user. I want to add few utility methods in class1 that only class2 can access. I searched a lot but I couldn't find any access modifier for method to grant access across different packages of same project only.
It there any chance to achieve it by any means?
UPDATE (Code example):
Class1 in package1:
package com.example.package1;
public class Class1 {
// This method should only be accessed by Class2, cannot made it public for
// every class
void performUtilityOperation() {
// internal utility
}
// other public methods...
}
Class2 in package2:
package com.example.package2;
import com.example.package1.*;
public class Class2 {
Class1 class1;
public void setClass1(Class1 class1) {
this.class1 = class1;
}
public void doSomeOperation() {
this.class1.performUtilityOperation(); // here this method is not
// accessible if not public
// do some other operations
}
// other public methods
}
Public methods inside a package class are public to classes in the same package. But, private methods will not be accessible by classes in the same package.
Yes. Well, obviously you can access those methods from within the same class.
The private modifier specifies that the member can only be accessed in its own class. 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.
Can a class declared as private be accessed outside it's package? Not possible. Can a class be declared as protected? The protected access modifier cannot be applied to class and interfaces.
There is no way to achieve this(nothing like friend
in C++ if that's where u r coming from). Although protected
members are accessible from a different package by an extending class as shown below:
package1
public Class1{
protected method();
}
Class2 extends Class1
and hence the method()
is visible in Class1
even if Class2 is in a different package.
package2
public Class2 extends Class1{
public otherMethod(){
method(); // is visible here
}
}
Class3
does not extend Class1
hence method()
will not be visible
package2
public Class3{
public otherMethod(){
method(); // not visible here
}
}
IMO this is the furthest you can go for hiding methods in Class1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With