Introduction to Object-Oriented Programming

Why have classes?

The obvious question one must ask is - Why do I need classes in the first place!?.

To answer this, let’s consider the following scenario -

There are N players in my soccer team and we track the number of shots taken by each player during the season and number of goals scored.

The variables for each player in this scenario will look something like this,

1
2
3
String name;
int shots;
int goals;

Instead of handling the three attributes separately, if we had a representation for a Player that had attributes name, shots, goals inside it, that would make life easier as everything would be in one package. We can calculate the successRate of a player if and when required.

We use a UML class diagram to represent a class design. It has three compartments -

  1. Top compartment: ClassName (begins with uppercase by convention, and are camelCased)
  2. Middle compartment: Instance Variables (variable names begin with lowercase by convention, and are camelCased).
  3. Bottom compartment: Instance Methods (method names begin with lowercase by convention, and are camelCased).
 

 

Thus, our Player class diagram looks like,

 

 

The reason we use text, integer and real as types (instead of String, int and double respectively) is because we don’t want to tie the class diagram with one particular language.

Once we have the design of a class, we can create objects of that class. For example, I might have multiple players on my team:

  1. Lionel Messi, Shots: 85, Goals: 27
  2. Gonzalo Higuain, Shots: 153, Goals: 4
  3. N’golo Kante, Shots: 7, Goals 1

We use a UML object diagram to represent a unique instance of the class. It has three compartments -

  1. Top compartment: objectName:ClassName (begins with lowercase by convention, and are camelCased)
  2. Middle compartment: Value of instance variables (variable names begin with lowercase by convention, and are camelCased).
  3. Bottom compartment: empty (instance methods are applied when needed).
 

 

Thus, the object diagrams for my objects are:

 

 

Similarly, a CarTrip entity can be described by two instance variables - distanceTravelled and timeTaken. Using these we can compute averageSpeed. We say averageSpeed is an instance method of the attributes.

How about DataPlan?

What are the instance variables for a Date entity? As in the calendar Date. What are the instance methods of the entity? Draw the class diagram.

SOLUTION

Instance variables: day, month, year. Instance methods: isLeapYear, daysLeftInYear, …

Draw the object diagram for an instance of Date entity that represents 19th April 2014

SOLUTION