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
}
}
How can a public method return the reference for the private instance to another class
Moderator: admin
-
- Posts: 20
- Joined: Fri May 01, 2020 11:27 am
- Contact:
-
- 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
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.
I would suggest you to go through a good book to understand the basics before attempting mock exams.
-
- Posts: 20
- Joined: Fri May 01, 2020 11:27 am
- Contact:
Who is online
Users browsing this forum: No registered users and 5 guests