Session 3 |
Introduction into object-oriented programming
Before we begin, here is a small introduction to object-oriented programming.
Most of our focus so far has been on procedural programming - breaking a complex task into smaller subtasks (methods). A method works as a separate part of a program and it can be called from anywhere in the program. When a method is called, execution of the program moves to the beginning of the called method. After the execution of the method is completed, the program continues from where the method has been called. This is the oldest style of programming and even in a language like Java we still use procedural techniques.
But Java has also a different approach to programming that we call object-oriented programming. In object-oriented programming, just like in procedural programming, we attempt to divide a program into smaller parts - objects with their states (properties) and behavior (methods).
Object-oriented programming involves a particular view of programming that has its own terminology. Let's explore that terminology.
- An object - a programming entity that has state and behavior.
- A class - a template for objects that defines a new data type; can contain class members: data members (state), methods, constructors, etc.
- An instance - a reference to an individual object.
There are three steps to create an object from a class:
- declaration - a variable declaration with a variable name and the object type.
- instantiation- the
new
keyword is used to create an object (allocates memory for a new object and returns a reference to the object it created). - initialization - the new operator is followed by a call to a constructor, which initializes the new object.
Reference: Adil Aslam lecture notes
Why to use objects?
It is quite easy to create primitive variables and assign values (e.g. int x = 5;
). If we want to operate on a series of ordered data of the same type, we use arrays (e.g. int[] a={1,2,3}
). What should we do if we want to group specific data of different data types? For example, a pet shop sells dogs. One of the dogs is a 3-year-old brown labrador Liza. In fact, we cannot create an array liza = {"Liza", "labrador", "small", 3, "brown"} because the values in the array are of different data types. Object-oriented programming allows us to group data of different data types under a brand new data type and store the data in a single variable. For example:
In this example, a brand new data type is Dog and various data about labrador Liza are stored in variable liza.
Used resources: MOOC "Object-Oriented Programming with Java: Chapter 21" by Arto Hellas, Matti Luukkainen.
Session 3 |