How can a public method return the reference for the private instance to another class

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
saregg
Posts: 20
Joined: Fri May 01, 2020 11:27 am
Contact:

How can a public method return the reference for the private instance to another class

Post by saregg »

public class Test {
private String writer;
private Data dd; //private instance reference variable
public Test(int val) {
dd=new Data();
dd.instt=val;
}
public Data getAuthor() {
return dd; // returning the reference of it to another class. Which is suppose to not happen, but happens Why ?
}
}
class TestC{
public static void main(String[] args){
Test tob = new Test(12);
Data oo = tob.getAuthor(); //reference returned here
oo.instt=12; //Access provided for private instance
}
}

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: How can a public method return the reference for the private instance to another class

Post by admin »

That's because you have a wrong understanding of access modifiers. Private simply prevents access to the variable. It has nothing to do with the object to which that variable points.
I would suggest you to go through a good book to understand the basics before attempting mock exams.


Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests