Page 1 of 1

About Question enthuware.ocajp.i.v7.2.917 :

Posted: Mon Oct 08, 2012 3:17 pm
by jorge.cardenas.salas
Given:
public class Square {
private double side = 0; // LINE 2

public static void main(String[] args) { // LINE 4
Square sq = new Square(); // LINE 5
side = 10; // LINE 6
}
}
What can be done to make this code compile and run?

Correct answer (according to the software Enthuware) is:
replace // LINE 6 with: sq.side = 10;
Because: side is not a global variable that you can access directly (Note that Java doesn't have the concept of a global variable). side is a field in Square class. So you need to specify which Square object's side you are trying to access.

My question is: given that side is already defined as private, it wouldn't be accesible even if I specified the object it belongs to, right? Or what am I missing here?

Re: About Question enthuware.ocajp.i.v7.2.917 :

Posted: Mon Oct 08, 2012 8:20 pm
by admin
Private members are accessible from the same class. The main method is within Square class, so you can access private member side of Square class from this method.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.917 :

Posted: Sun Aug 02, 2015 4:00 pm
by jadam81
admin wrote:Private members are accessible from the same class. The main method is within Square class, so you can access private member side of Square class from this method.

HTH,
Paul.

This would be good to put in the explanation. Cleared up a lot of confusion.

Re: About Question enthuware.ocajp.i.v7.2.917 :

Posted: Sat Dec 05, 2015 3:42 pm
by deniscapeto
I agree with jadam81. The explanation could be more clarifying.

another good comment in explanation could be:

if the field side in LINE 2 was static, the code would work perfectly.

Re: About Question enthuware.ocajp.i.v7.2.917 :

Posted: Sat Dec 05, 2015 8:17 pm
by admin
Added.
Thank you for your feedback!