Goals

  • To understand basic objects
    • To describe objects
      • Fields
      • Methods
      • Constructors, this keyword
    • To use objects
      • new keyword
      • To call an object's methods
"Actually I made up the term “object-oriented”, and I can tell you I did not have C++ in mind." ~ Alan Kay

Object-oriented Programming

In English we refer to a bicycle, a dog, or a car as "things" or "objects." "Object" is a generic term. In programming, we can create objects too. Objects can refer to concrete ideas like a particle or a bicycle or to more abstract ideas like a physics solver or a transport simulation.

class Bicycle{

}

In general,
class ClassName{

}

We use classes to create user-defined types.
Capitalize the names of classes.

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 stores its location, 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.

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 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.
Constructors have the same name as their class, and no return type.

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.