Introduction to Object Oriented Programming Pt I

Introduction

A program, any program, consists of two things – DATA and FUNCTIONALITY. In a word processor for example, there is data such as the text of the document, the font type, size and colour, and so on. Then there is the functionality such as loading the document from disk, adding, deleting and changing the text, and saving it to disk. Typically the functionality is provided by the code you write, and the data is stored in variables of various types (strings, integers, arrays and so on).

Object Oriented Programming is a way of organizing the data and functionality of a program into smaller, well defined and easily manageable blocks. This makes writing and maintaining the program quicker and easier.

For the purposes of this tutorial we will assume you are already familiar with the general concepts of programming. We are just looking at the concepts here and not any specific language, and any code we write will be a generic ‘pseudo-code’ that can be easily converted into any of the modern languages (C#, java, php, etc.)

paint

For an example, let us suppose that we are writing a simple graphical drawing program, something like Microsoft Paint. The user can add lines, rectangles, circles etc. to a canvas to build up a picture, and can save the picture to disc or load an existing one.

Objectobject

An object is a self-contained ‘thing’ that has very tightly defined data and functionality.

For example, if our user draws a rectangle, then that rectangle has data (its position, size, and colour) and some functionality (we can create a new one, delete it, rotate it, etc.) We call this rectangle an ‘object’. Note that there may be many rectangles drawn on our canvas – each one is an individual object of type ‘rectangle’, each with its own position, size and colour. There may be other objects too, such as lines and circles.

Classes

The type of an object (line, rectangle, circle) is know as it’s ‘Class’. A Class is really a definition or a description of an object, and very clearly defines what data it contains and what functionality it provides. In general, the data values of a class are known as its ‘properties’ and its functionality is defined by ‘methods’.

Our rectangle class could be loosely defined as:

When our user gets busy, he creates many rectangular objects on his drawing. Each one is an ‘instance’ of the Rectangle class. When we create a new instance of the Rectangle class, we could say we ‘instantiate’ a new Rectangle object. We end up with many objects of the same class.

Note that an ‘object‘ is an ‘instance of a class‘. Often the terms ‘object‘ and ‘instance‘ are used interchangeably.

References

When we create a new object in code, the computer allocates some memory for that instance to store all its data. Each instance gets its own allocation of memory space where it keeps its own ‘instance’ data (eg. position, size, and colour). Since we may have many such instances, we need a way of referring to the specific one we want. We get a ‘reference‘ to that instance which is in fact just a memory address pointing to where that instance is stored in the computer’s memory. We don’t really care where it is so long as we have a note of it so we can get at it again. We store this reference in a variable.

In most languages, each variable is defined with a specific data type. Common types are ‘integer’, ‘string’ and ‘boolean’ but there are many more. When we define a Class, we automatically create a new data type just for that class. When we want to keep track of a reference to an object, we declare a new variable of type ‘whatever the class is’, so we would declare a variable of type ‘Rectangle’ in which to store a reference to a Rectangle object.

Having a new data type just for that class is useful because it lets the programming environment know what type of object we are talking about.

For instance, in most languages a string is in fact a class, and when you define a new string variable you are creating a variable of type ‘String’ in which to store a reference to the string you create.

This is telling the programming environment that you are creating a new instance of the ‘String’ class, and you want to store a reference to it in the variable ‘myNewString’, and you want its initial value to be “some text”. The variable ‘myNewString’ doesn’t actually hold the characters itself, instead it contains a number – the address of a block of memory which contains the characters ‘some text’. It is a reference to this particular instance of the String class.

Because the programming environment knows myNewString is of type ‘String’, when we do something like

it doesn’t just print the memory address itself (a number), it goes and fetches the characters from that memory and prints them instead. Also you will probably find that if you start typing myNewString followed by a full stop (period) the programming environment will offer you a list of things you can do with that string. One of these will be the ‘length’ property. You can type:

and you get the answer 9. What you have actually done is asked for the value of the ‘length’ property of that instance of the String class. Because the programming environment knows that myNewString is of type String it will help by listing all the properties and methods of the class while you are writing your code (very helpful).

Properties and Methods

From our Rectangle class above you can see that properties are values which describe some aspect of the object, and usually we can set them or read them. For example, if we had a Rectangle object ‘myRectangle’ we could set or read it’s colour as follows:

(Yes, I know I’m spelling colour wrong, but most programming languages have been delveloped in America where they like to keep their words short – and it does save a bit of typing!)

Accessing a property may or may not ‘do’ something, but always sets or returns a value. By ‘do’ something we mean perform some action or calculation. For example, setting a property might include running some code in the class which checks the value supplied is within legal limits. Reading a property might involve a calculation such as calculating someone’s age when the class data contains only their date of birth. But generally properties are there to set or read values of various properties of the object.

Methods on the other hand are actions to perform. Methods might or might not take parameters and might or might not return a result (usually not). In the above examples, move(x,y)  is a method of the Rectangle class. When we call this method we must supply two parameters: the distance to move in the x and the y directions. A call to this method would look something like

Properties and methods are defined within the class definition. All the code that is run when calling these properties or methods is contained within the class definition. All the variables used to hold the values of the properties (and any other data that an object needs are contained within the class definition. A Class is a self-contained block of code which comprises all the data and all the functionality pertaining to the object it represents.

Constructors

When you instantiate a new instance of a class the runtime has to allocate some memory to hold all the data for that instance of the class. This is handled by an internal method called a ‘constructor‘ which is responsible for building the object for you. Every class has a default constructor which is generated automatically by the programming environment and which is hidden from us, and it handles all the low level stuff like allocating memory and keeping tabs on how many objects have been created – stuff we don’t really need to know about.

But you might also want to do some processing to set up various things when an object is first created. Imagine we want to create a new rectangle at position (10,10) and size 5 wide and 3 high. We could write:

This instantiates a new Rectangle object and holds a reference to it in the myNewRectangle variable. It then sets the position, width and height properties to the values we desire. However, this is quite a lot of typing and it would be quite convenient if we could do it all at once. After all, it is likely that every time we create a rectangle we will want to set its size and position. Therefore we can write our own constructor which takes some parameters and does it all in one. As part of the class definition, we write:

Here we have defined a new method called Rectangle(x, y, width, height)  which takes four numbers as parameters. It then sets the position, width and height properties to those values. We can now instantiate a new rectangle like this:

When we define a method with the same name as the Class, it is called as a constructor. In fact, the original default constructor runs first to create the object, and then our constructor is called to perform whatever initialization actions we want (like setting various property values).

Notice how, within the class methods themselves, we refer to the properties as this.width  etc. this  is a generic shortcut for ‘this object’ and we use it whenever we want to use one of this object’s properties or methods from within the class code itself.

Overloading

Now, what if we also want to set the colour when we create our rectangle object? We can define another constructor as follows:

Now we have two constructors – two methods, both with the same name but taking a different number of arguments. When we instantiate a new object the programming environment looks at our method call and works out which of the two constructors to call based on the number of arguments.

The ability to have several methods of the same name but with a different number of arguments is called ‘overloading‘ and is very handy.

In Practice

This is a simple overview of the basics of programming with objects. It would be useful to have a quick look at how this might appear in practice. First, we will define our Rectangle class. Usually we put class definitions in separate files – this is not mandatory but is useful in keeping things organized and also lets us easily re-use a class in another program.

Our class file might look something like this:

This is a little simplified, but shows the main concepts.

In this case our properties are just variables defined in the class. We should really include code to check the values are legal (eg. that sizes are >0 or rotation within +/-360 degrees) but have not bothered this time.

Notice that the position property is defined as type Point . This is a data type which is defined by the programming environment on most systems, and is itself a class. That is why we use the new  keyword when we create an instance of it to hold the position of our rectangle.

We set default values for all our properties. This is so that if our class is instantiated using the default constructor, all our properties still end up with sensible values. If it is instantiated using either of our constructors, these default values will be overwritten with the user supplied values.

The move and rotate methods both update the relevant properties and then call the draw()  method which re-draws the rectangle in the new position. (Note that for simplicity we haven’t tried to delete the old rectangle, just drawn a new one, so this isn’t actually very workable but at least gives the general idea).

The draw()  method uses some library methods which are defined by the programming environment. These will differ depending on what platform and language you are using, but most programming environments include something similar. We use the Canvas methods to move our ‘pen’ and then draw four lines (up, left, down, and right) to draw the rectangle. We apply some maths to work out where we want to draw each line to taking into account the rotation and size properties.

To use our new class in our main program we would have something like this:

Of course if we were writing a Paint program we would not be hard-coding our rectangles like this. We couldn’t assign a separate variable to each one (like blueRectangle and blackRectangle above) because when we write the code we have no idea how many rectangles we will need. In a situation like that we can use an array to hold a collection of these objects and add new ones to it whenever we need to.

Note that the syntax for using arrays is very different language to language and so the above psuedo-code may look nothing like what you need, but you get the idea.

So, that is the first part of our introduction to Object Oriented Programming. In Part II we will look at some of the more mysterious and arcane principles of objects and explain some of the buzzwords you might hear like encapsulation, inheritance, and more.

 

Author: sp_admin

Share This Post On