user3762742
user3762742

Reputation: 97

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!

Upvotes: 1

Views: 5532

Answers (3)

James
James

Reputation: 338

public and private are access modifiers. If use use private modifier it means is that, the relevant member can only be accessed within the same class. If it is public you can access that member in same class, same package and different package; simply everywhere. OOAD suggest we should encapsulate what varies. So we make all the instance variable private and declare public getter/setter methods to access those variables from anywhere. public and private are just modifiers.

Upvotes: 0

indika
indika

Reputation: 923

public and private are access modifiers. They are optional modifiers and they decides the accessibility of variables,methods or classes. If use use private modifier it means is that, the relevant member can only be accessed within the same class. If it is public you can access that member in same class, same package and different package; simply everywhere. OOAD suggest we should encapsulate what varies. So we make all the instance variable private and declare public getter/setter methods to access those variables from anywhere. public and private are just modifiers.

Upvotes: 0

user2357112
user2357112

Reputation: 280291

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

Upvotes: 6

Related Questions