How to use a private method in Java

Dan picture Dan · Oct 8, 2011 · Viewed 31.2k times · Source

I am given a class that has a private method say setCoors(int x, int y). The constructor of that class has the setCoors in it too. In a different class, I want to have a method setLocation which calls setCoors. Is this possible?

New Question:

If I am not allowed to set the method to public, is this possible?

public class Coordinate{
    public Coordinate(int a, int b){
        setCoors(a,b)
    }
    private void setCoords(int x, int y)
}

public class Location{
    private Coordinate  loc;
    public void setLocation(int a, int b)
        loc = new Coordinate(a,b)
}

Answer

Ray Toal picture Ray Toal · Oct 8, 2011

The best and most helpful answer depends on the context of the question, which is, I believe, not completely obvious.

If the question was a novice question about the intended meaning of private, then the answer "no" is completely appropriate. That is:

  • private members of A are accessible only within class A
  • package-private members of A are accessible only within classes in A's package
  • protected members of A are accessible only within classes in A's package and subclasses of A
  • public members of A are accessible anywhere A is visible.

Now, if, and okay maybe this is a stretch (thank you Brian :) ), that the question came from a more "advanced" context where one is looking at the question of "I know private means private but is there a language loophole", then, well, there is such a loophole. It goes like this:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

class C {
    private int x = 10;
    private void hello() {System.out.println("Well hello there");}
}

public class PrivateAccessDemo {
    public static void main(String[] args) throws Exception {
        C c = new C();
        List<Field> fields = Arrays.asList(C.class.getDeclaredFields());
        for (Field f: fields) {
            f.setAccessible(true);
            System.out.println(f.getName() + " = " + f.get(c));
        }
        List<Method> methods = Arrays.asList(C.class.getDeclaredMethods());
        for (Method m: methods) {
            m.setAccessible(true);
            m.invoke(c);
        }
    }
}

Output:

x = 10
Well hello there

Of course, this really isn't something that application programmers would ever do. But the fact that such a thing can be done is worthwhile to know, and not something that should be ignored. IMHO anyway.