Page 1 of 1
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Fri Jan 04, 2013 9:36 am
by Ryhor
Don't think this is a point of this question. Here method's parameter of type A can access private member only because the method is declared in the same class as parameter type is. Looks like breaking encapsulation principles a little bit.
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Tue Aug 12, 2014 5:00 pm
by bluster
An attempt to implement the (supposedly faulty) code seems to have worked. I assume I messed up in the implementation, and ask if someone can point out where it went astray. The code below compiles and spits out 20.
Code: Select all
class A
{
private int i;
public void modifyOther(A a1)
{
a1.i = 20; //1
System.out.println(a1.i);
}
public static void main (String[] args) {
A first = new A();
A second = new A();
first.modifyOther(second);
}
}
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Tue Aug 12, 2014 7:26 pm
by admin
Not sure what is your question. The code is fine. private means private to the class not to the object. So it is possible for one object to modify other object's private member if they are of the same class.
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Thu Aug 21, 2014 10:57 am
by bluster
Got it. Thanks for explaining.
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Tue Apr 14, 2015 1:11 am
by pfilaretov
Although I knew the right answer, as Ryhor I wonder, doesn't that break incapsulation principles?
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Tue Apr 14, 2015 1:38 am
by admin
pfilaretov wrote:Although I knew the right answer, as Ryhor I wonder, doesn't that break incapsulation principles?
Depends on how you look at it. Java designers certainly accepted it as good enough encapsulation
-Paul.
Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Tue Apr 14, 2015 1:53 am
by pfilaretov
that's funny

Re: About Question enthuware.ocpjp.v7.2.1469 :
Posted: Mon May 23, 2016 7:02 am
by Nisim123
I thought about how does the compiler know whether the object that is being sent to a method is not only a reference type
and that it is a real actual object?
so i assumed that the object of type A should be build first inside the method, and then be accessed in the given manner,
otherwise the accessed variable modifier should have been static.
something like the following for a variable that is not defined static:
Code: Select all
class A {
private int i;
publid void modifyOther(A a1) {
a1 = new A() ;
a1.i = 20 ;
}
}
And for a variable that is defined static the code as provided in the question might be enough:
Code: Select all
class A {
private static int i ;
publid void modifyOther(A a1) {
a1.i = 20 ;
}
}
But i guess that the compiler does check whether the object being sent to a method is only a reference type or a real object.
