Instance Variables
DefN: Instance variables are variables that “belong” to an instance of an object. An instance variable is declared inside the class but outside of any particular method. Each instance of an object carries its own value of the variable. Instance variables are also referred to as member variables (as in: the variable is a “member” of the class).
REMARK: if you call had robot instances “bob “and “lisa” and you issued the following commands:
bob.move();
lisa.move();
you would expect that move would be run on each particular instance. That is, bob moving is distinct from lisa moving.
The same is true for instance variables. If the class has declared an instance variable called “foo” I would expect that bob.foo and lisa.foo refer to bob’s foo variable and lisa’s foo variable respectively — not the same value.
DefN: a member variable’s “visibility” can be set as public, private (or protected). If an instance variable is private it means that only methods within the class have the ability to “see” the variable and modify it. If an instance variable is declared public it means that anything can directly access the variable inside the instance.
Private instance variables are the most common. This is because often instance variables are used to keep track of important information about the state of an object. That is, the variables are only modified internally by the code in the class. If public access were given the internal information could be inaccurate.
It is considered good practice to keep as much of a class private as possible (both methods and variables). The only things that should remain public are those things which you want users of the class to be able to do.
For examples please see the demo project from 10.07.07
Leave a Reply
You must be logged in to post a comment.