Michael
Michael

Reputation: 4461

Aliasing issues (public reference to a private object inside a class)

I'm reading Thinking in Java. The chapter about access (private, public etc.). This is a quotation from the book:

...just because a reference to an object is private inside a class doesn't mean that some other object can't have a public reference to the same object.

Then we are redirected to the online supplements for the book to learn about aliasing issues.

On the official site there is a solution guide for the book. But it is expensive for me.

Could you clarify what is meant by that aliasing issues so that I could google more examples.

Upvotes: 1

Views: 90

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280072

Here's an example

public class Foo {}
public class PrivateExample {
    private Foo foo;
    public PrivateExample (Foo foo) {
        this.foo = foo;
    }
}
public class PublicExample {
    public Foo foo;
}
...
// in some method
Foo foo = new Foo();
PrivateExample privateExample = new PrivateExample(foo);
PublicExample publicExample = new PublicExample();
publicExample.foo = foo;

Now both the PrivateExample instance and the PublicExample instance have a reference to the same Foo object. Note that even the method has a reference to the object. So even though you can't access it through the PrivateExample instance, you have access to it through the others. It is not necessarily safe.

Upvotes: 6

Related Questions