More about variable scope (section)
What are static vs non static variables? what is variable scope?
You must be signed in to leave a comment
28 February 2022, 11:17
1) "static". (variable 'count'). This means: this variable belongs only to its own class. It doesn't belong to any object. Other name: class-variable. You can create objects from the class Cat, but the static 'count' variable will not be the part of any cat-object! 2) "non-static": (age, name): these variables belongs only to the Cat-objects. Other name: instance-variable. (instance = object) If you don't create any Cat-object, then these variables don't even exist! If doesn't exist any Cat-object, then you can't use these variables. No one can do anything with these variables. Only the created objects can do something with them. The nonstatic variables are just a pattern for future objects. The first existing thing is static: The JVM starts the program run with the STATIC main method. This static main method (and all the other static method) can access/call/run only the static variables and static methods. They can not access the non-static variables or non-static methods. The non-static variables and methods are accessable only by objects, after if you created an object in the static main method. (Or, the static main method calls an other static method, and you will create an object inside this static method.) Non-static (instance)methods/variables can use the static (class)variables/methods. But static (class)methods/variables can not use the non-static variables/methods. When the program use the class Cat at first time, the static count variable will be inicialized to zero (zero is the default value.) But the nonstatic (instance)variables (age,name) will be inicialized only if you create a Cat-object. These topics will be explained in more detail later in the course. Also the scope topic.