2. Class and Object
A class is a software entity that has internal data and a set of methods or functions that act upon that data.
An object is a class 'instance', which means a copy of the class has been created in memory and has been assigned a name in order to reference it.
A typical class looks like this
class Box() { private var width private var height public function Box() { var myBox = new Box } public setHeight(x) { myBox.height = x } public setWidth(x) { myBox.width = x } } |
In this case a class called Box is defined. This class has two private variables within it called height and width.
These variables cannot be changed directly by any code outside the class. However functions setHeight and setWidth have been defined that will set the respective height and width of the object.
Notice there is a function also called Box within the class. This is how an object is created. This is called the 'constructor' function. When called, a copy of this class is created in memory and given a name by the calling code. Another word for this object is an 'instance'.
The main software will 'instantiate' an object of class Box like this
Main program { theBox = Box() theBox.setHeight(20) } |
In this example, an object called 'theBox' has been instantiated i.e. an object in memory has been created that has the characteristics of class Box. The next line calls the object's setHeight method in order to set the height of the box. There could be many methods defined within a class.
In order to manipulate an object, an 'interface' is defined. The class interface lists all the methods available within that class and all the parameters they require.
In this way the class can act as a black box - all the programmer needs to know is how to create an object and how to call its methods. The internal workings of the class is of no concern.
Challenge see if you can find out one extra fact on this topic that we haven't already told you
Click on this link: Class Design patterns
Copyright © www.teach-ict.com