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?
About Question enthuware.ocajp.i.v7.2.917 :
Moderators: Site Manager, fjwalraven
-
- Posts: 1
- Joined: Mon Oct 08, 2012 3:15 pm
- Contact:
-
- Site Admin
- Posts: 10055
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.917 :
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.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 2
- Joined: Sun Aug 02, 2015 3:54 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.917 :
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.
-
- Posts: 6
- Joined: Wed Dec 02, 2015 5:50 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.917 :
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.
another good comment in explanation could be:
if the field side in LINE 2 was static, the code would work perfectly.
-
- Site Admin
- Posts: 10055
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.917 :
Added.
Thank you for your feedback!
Thank you for your feedback!
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 20 guests