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?
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() { ... }
}
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
}
}
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