5

我得到了一个具有私有方法的类,例如 setCoors(int x, int y)。该类的构造函数中也包含 setCoors。在另一个类中,我想要一个调用 setCoors 的方法 setLocation。这可能吗?

新问题:

如果我不允许将方法设置为公开,这可能吗?

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)
}
4

6 回答 6

7

最好和最有帮助的答案取决于问题的上下文,我相信这并不完全显而易见。

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.

于 2011-10-08T05:31:09.330 回答
5

不,private意味着该方法只能在定义它的类内部调用。您可能希望setLocation创建该类setCoords所在的新实例,或更改setCoords.

编辑:您发布的代码将起作用。请注意,Location该类的任何实例都将绑定到它自己的Coordinate对象。如果您在代码中的其他位置创建新Coordinate对象,您将无法修改其内部状态。换句话说,线

Coordinate myCoord = new Coordinate(4, 5);

将创建myCoord永远具有坐标4和的对象5

于 2011-10-08T05:28:03.670 回答
4

private意味着它是私人的

如果您希望其他类调用它,也许您不应该将其设为私有?

于 2011-10-08T05:26:55.473 回答
3

没有private方法不能在定义它们的类之外访问

于 2011-10-08T05:28:12.453 回答
3

Kid-doing-homework: the answer is no. Guy-requiring-some-crazy-work-around-for-his-job: the answer is yes. Far more importantly though, Your setCoors method should not take int arguments. It should take two SilverBullet objects.

于 2011-10-08T05:50:10.090 回答
1

private意味着您只能在定义的类中访问它。

于 2011-10-08T05:29:53.640 回答