Skip to content

Can a object be private and public?

Can a reference to an object be private in class while other object can have a public reference to the same class(post script: new to java+ a simple example please). I read somewhere that this prob is regarding aliasing? Sorry my title may not make sense!



Objects aren’t private or public. Fields can be private or public. Fields can hold references to objects. An object can be referred to by both private and public fields simultaneously:

public class Example {
    public static Object a;
    private static Object b;

    public static void main(String... args) {
        Object foo = new Object();
        a = foo;
        b = foo;
        // Now our Object is referred to by the public field a, the private
        // field b, and the local variable foo (which is not considered either
        // private or public).
3 People found this is helpful