Can someone please tell me why a class and not an object can be used to access a variable declared in it's method?
I know an object which is an instance variable can be used to access the variables and methods of it's class but using a class to do that directly is a bit confusing for me.(Here is a reference to what i mean: level 4 lesson 1: Apple.applePrice where Apple is a class)
Hi i am a bit confused with this.
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
16 April 2019, 13:47useful
In that lesson applePrice is a static variable meaning that it is a shared variable over every Apple object. You can access it using a variable or the class. You have already been accessing static methods in the same context as static variables, for example:
System.out.println()
You never have to declare an object before you can use the println method in the System.out class.
If applePrice was not static then you would not be able to access it using the class. As i said above, and mention again here because it is important, is that static variables are shared over every object of the same type. Take this bit of code for example:
At stop point 1 I have declared 3 Apple objects. At this point applePrice for all three is 0 (assuming that it isn't initiated to anything other than 0 in the class, or changed by constructor).
At stop point 2 I have used the Apple class to increase the applePrice variable by 1. Now applePrice for apple, apple2, and apple3 all equal 1.
At stop point 3 I have used the object apple2 to increase applePrice by 1. Now the applePrice variable for all objects is equal to 2.
At stop point 4 I have used the apple2 object again to set applePrice to the value of apple.applePrice + apple3.applePrice. Because applePrice for all objects is 2, this equates to set applePrice to 2+2.
Appleprice would return 4 for all objects or the class if you ran this code and used Sys.out statements at the stop points.
+1
Godwin
16 April 2019, 14:17
Thank you so much for breaking it down for me, it is much clearer now. I am grateful.
+1