Reputation: 103
I have two classes:
public class Class1{}
public class Class2{
private void simpleMethod(){ /*...*/ }
}
In Class2
I have private method simpleMethod()
and I want to use it in Class1
in the same project. I don't want rename this method as public
because I don't want to show it in my API. Can I create public
method without showing it in API? Or, something else?
Upvotes: 7
Views: 8557
Reputation: 9059
If Class1
and Class2
are both in the same package you can simply remove the private
modifier, making the method package-private. This way it won't be exposed in the API and you will be able to access it from Class1
.
Before:
public class Class2 {
// method is private
private void simpleMethod() { ... }
}
After:
public class Class2 {
// method is package-private: can be accessed by other classes in the same package
void simpleMethod() { ... }
}
Upvotes: 13
Reputation: 1858
Well, another way to go would be to have two different interfaces. One for your public API and one for your internal API, your object of Class2
would implement both. Everybody who deals with the API will talk to it through the public interface you exposed
public class Class2 implements PublicApi2 {
public void somePrivateMethod() {
...
}
@Override
public void somePublicMethod() {
...
}
}
(didn't implement two interfaces in here, as the matter of fact there is no need for a 'private one' since objects of your library/framework/whatever can deal with concrete classes instead, but that is up to you)
Clients will always reference your object as being of type "PublicApi2" and never deal with the concrete implementation (Class2) while your internal clases would.
Upvotes: 3
Reputation: 317
Apart from above scenario, you can use reflection API to access private method as below:
Class a = Class.forName("");
Method method = a.getDeclaredMethods()[0];//retrieve your method here
method.setAccessible(true);
Upvotes: 3
Reputation: 2040
Use either protected
or omit the access modifier completely.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Upvotes: 1
Reputation: 85789
If both classes are in the same package, then you can leave simpleMethod
with default visibility, so it can only be used by the class and the classes in the same package.
package org.foo;
public class Class1 {
//visibility for classes in the same package
void simpleMethod() { }
}
package org.foo;
public class Class2 {
public void anotherMethod() {
Class1 class1 = new Class();
class1.simpleMethod(); //compiles and works
}
}
package org.bar;
import org.foo.Class1;
public class Class3 {
public void yetAnotherMethod() {
Class1 class1 = new Class1();
class1.simpleMethod(); //compiler error thrown
}
}
Upvotes: 8