Object Oriented Programming Tutorial - Part Two, , November 2002
So lets quickly recap what we have here. An object is an instance of a class. All instances can have their own variable values and can exist completely unaware, and unaffected by the other instances. To create an instance we use the new operator along with the proper constructor call.
Now we have our Animal instance called anim and it has values that we have passed into the instance via the constructor so how do we then get things out? Ahhh, fear not we have the means! In all object oriented languages getting a variable or calling a method is done by the dot (.) operator. So, to get the height in our object we would do something similar to this: int myHeight = anim.height; Note we use the class variable we used to create the object (anim) followed by the . followed by the variable we wish to access. Similarly we can change a variable in our object by accessing the variable, like this: anim.height = 6; We will see in a bit that this isn't a great idea and very poor design.
Now let's do something with these methods we built so we can access them. Click Here to see our added implementations. Now we can call our methods to get some functionality out of this class. To make our animal eat we simply call our eat method like this: anim.eat(); Calling the sleep method requires that we pass a variable to test our condition so we would call this method like this:
int timeToSleep = 10;
anim.sleep(timeToSleep);
Our sleep method now accepts the parameter (timeToSleep) to control our loop. Our animal "sleeps" until it breaks out of our loop.
Encapsulation
As I mentioned before directly accessing variables is not a great idea. From this comes the concept of encapsulation. We don't want anything to accidentally change the values in our variables and we definitely don't want an outside party to get to them. This is handled by making our variables private to the class and creating methods to change them. These are called accessors and mutators, more commonly know as setters and getters. Click Here to see how we have changed the class to accomplish this. Now don't get crazy about the amount of code we have added to this version of our little class because they are all basically duplicates of the same code for each variable we have defined. Note also that we have changed the access modifiers for our variables to private. Now they cannot be accessed from anywhere outside of our class, effectively encapsulating our data. Anyone attempting to change them must now use one of our public set or get methods. These methods are really quite simple, the set method allows you to change the variable, the get returns the value contained in the variable. Of course these setters and getters can be made much more complicated, demanding proper input, security etc. but we need to keep it simple for now.
Lee Ritenour Staff, leeritenour.com | More Testimonials >>