Page 1 of 1

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

Posted: Sun May 03, 2020 1:10 am
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
}
}

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

Posted: Sun May 03, 2020 6:57 am
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.

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

Posted: Mon May 04, 2020 1:16 pm
by saregg
Thank You!