Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using private method from another class in Java

Tags:

java

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?

like image 698
Igal Rozman Avatar asked Apr 15 '15 20:04

Igal Rozman


2 Answers

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() { ... }
}
like image 163
Anderson Vieira Avatar answered Nov 13 '22 14:11

Anderson Vieira


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
    }
}
like image 41
Luiggi Mendoza Avatar answered Nov 13 '22 12:11

Luiggi Mendoza