Back

Object Oriented Programming

Reading

The moment a person forms a theory, his imagination sees in every object only the traits which favor that theory. [Thomas Jefferson]

Object-oriented Programming

In life we refer to a bicycle, dog, or car as "objects". In programming, we can create objects too. Objects can refer to concrete ideas like a particle or to more abstract ideas like a back account. The word class refers to the definition or "blueprint" of an object. The terms object and class often refer to the class.

Here's how to set up a class to define a new object:

We use objects to create our own "custom" data types.
Capitalize the first letter of every word in your class name, ex: MyNewClass.

Fields

  • To store data in objects, we use fields.
  • When an object contains some data, we say that the object encapsulates data.
  • Saying that an object encapsulates data is fancy way of saying that an object "has" some data. It might have position information or a colour.

Let's add two fields to our Bicycle class.

We use fields to store data in an object.

Methods

Now that our bike knows where it is, we need to give it the ability to do something. Let's add two methods to our object a method for drawing our bike and one for moving it.

Constructors

A constructor is a special type of method that is called during the creation of an object. Notice that it does not have a return type. In the constructor, we take care of setting up the object by initializing the values of variables. We can overload constructors too. They are just functions. We might overload the constructor to provide two different ways of creating a bicycle - one where the position is set to (0,25), and one which allows you to decide.

An example of a constructor, and overloaded constructor:

Did you notice our use of this? this is a keyword that allows an object to refer to itself. It is sort of like saying "me". In our example, we use this to make a distinction between the object's xPos and yPos from the constructor's parameters. this allows the program to know to which one we refer. If we didn't do make this distinction, we would get an error because you can't have two variables in the same scope with the same name.

Methods allow objects to do things.
A constructor is a special method used to create an object and can be overridden.

A Little Theory

When we create an object, we create a reference variable.The reference variable points to the address of the object in memory. When we use the new keyword a reference to the object is created. The new keyword calls the constructor and returns the address of the new object in memory.

This newly create object is called an instance.

Bicycle myBike = new Bicycle();

Variables that are instances of objects are references to the object in memory. We call them reference variables.