Using private methods from another class in Java

I have two classes:

public class Class1{}
public class Class2{
    private void simpleMethod(){ /*...*/ }
}

In class2, I have a private method simplemethod (), which I want to use in Class1 of the same project I don't want to rename this method public because I don't want to display it in my API Can I create a public method without displaying it in the API? Or something else?

Solution

If both Class1 and class2 are in the same package, you can simply delete the private modifier to make the method package private In this way, it will not be exposed in the API. You can 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() { ... }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>