smahale wrote:Thanks. And appreciate your clarification that a Square object will not be necessary. 'Square.side' should do.
However if I do have an object, this static 'side' is also available through the object, correct?
Corrent.
Just to add more context to my question, I got confused because in a class, the private member variables are all accessible through getters and setters, without having to use an object reference. And in our case we had to use an object reference for 'side' in our main method.
Instance variables (whether public or private, doesn't matter) can ONLY be accessed through a reference to an object of that class. When you try to access instance variables from within an instance method of the same class (for example, from getter or setter methods), you do not have to type the reference to access those variables because an implicit variable named "this" is added by the compiler. So even though you are not typing the reference name, the reference is there. For example, if you have a private instance variable named value in a class, the following two getter methods are equivalent -
Code: Select all
private int getValue(){
return value; //did not use a reference name here so "this" will be added by the compiler
}
private int getValue(){
return this.value;
}
We had to use a reference variable sq to access side because main is a static method. Static methods are not executed in the context of an object and so there is no "this" variable for the compiler to add. That is why you need to tell the compiler which object's side do you want to access.