Understanding OOP in Java (Classes, Constructors and Objects)

In this first article of the series ‘Understanding Object Oriented Programming in Java’ and in subsequent articles, I’m going to make understanding OOP as painless as possible, by ‘speaking’ in simple terms and code examples in Java. In this article, I assume you have at least, basic knowledge of Java programming. Let’s just get right to it.

Photo by Alvaro Reyes on Unsplash

I’d like to paint a picture of POP against OOP and why we choose OOP as understanding this would provide a line of thought when approaching any OOP problem. The idea behind traditional POP in solving a problem is to break the problem down and solve(code) in a step-by-step approach. Say, we want to create a Bank management software for customers; it’s going to include a signup/login page, details of which would be stored in a database, etc. In POP, we write codes or functions doing all these in chronological order till the end. This looks like a really great idea until you need to design a similar system for admin and employee management, then you need to repeat this process again by writing code for a signup/login page that would store details in a database all over again. It gets really tiring and this is where OOP saves the day; through its state-of-the-art programming model through the use of objects whose contents and behaviors is defined by a class. With OOP, you don’t need to write the same code for the employee management system from the example above, defining classes and creating objects allows you to call and reuse codes to perform recurring functions and save time. Other advantages of OOP is that it makes it easier to spot bugs because your code is organized and you know where to look, flexibility as a defined function can adapt to solve a similar problem(polymorphism) and easy maintenance of your project. The four main pillars of OOP are abstraction, polymorphism, encapsulation and inheritance. I will explain these concepts with examples in this series of articles.

Classes are templates/blueprints from which objects are created. They contain set of fields and methods used to define the state and behavior of an object.

A class is defined with the following syntax;

<access modifier> class <name> {
//fields
//methods
}

A class can only have either of two access modifiers: public or default. I will talk more about access modifiers in the next article of this series. An example of a defined class is;

public class Car {
String brand;
double price;
int maxSpeed;
public void changeGear(){
System.out.println("Gear Change");
}
public void turnLeft(){
System.out.println("Left turn");
}
}

Here, the variables brand, price and maxSpeed define the states in this class while the methods changeGear() and turnLeft() define the behaviors in the class Car.

To buttress the meaning of states and behaviors, I’ll use the Car class above as an example. We know what cars are, and we know there are different kinds of cars; what do all cars have in common anyways? brands, prices, plate numbers and so on. They also carry out common functions; they move, accelerate, turn left or right. In this analogy, Car is a general name (class) whether its a Tesla or a Lamborghini, they all have brand names and prices which is known as the ‘state’ of the car and they perform the same function i.e moving aka ‘behaviors’. In reality, softwares also have states and behaviors.

A class can have of 3 different type of variables;

  • Local variable: This is a variable declared and initialized in a method, block or constructor of a class.
  • Instance variable: This is a variable initialized within a class but outside any method, block or constructor. It can be accessed by any method in the class.
  • Class Variable: This is a variable declared with the static keyword within a class but outside any method, block or constructor.
class Car {
String brand; // Instance Variable
double price;
static int maxSpeed; // Class Variable
int setSpeed(){
int initialSpeed=0; // Local Variable
return initialSpeed + 15;
}
}

From the Car example above, say the car in question is a particular Tesla, this Tesla is known as an ‘object’. An object is known as the instance of a class. An object is defined by the following syntax;

ObjectReference = new Constructor()

Creating an object of the class Car above;

Car tesla = new Car();

A breakdown of the code above;

  • Car’ refers to the name of the reference class
  • tesla’ is called the reference variable, which is the name of the object
  • new is a keyword for defining objects
  • ‘Car()’ is the constructor of the class. I’ll talk about constructors in a bit.

Instance variables an methods can be accessed with objects by

ObjectReferenceVariable.variableName;
ObjectReferenceVariable.methodName()

An example is given below

public class Car {
int maxSpeed;
public void setMaxSpeed(int speed){
maxSpeed = speed;
}
public int getMaxSpeed(){
System.out.println("Maximum speed is "+maxSpeed);
return maxSpeed;
}
public static void main(String [] args){
Car tesla = new Car(); // creating object
tesla.setMaxSpeed(200);
tesla.getMaxSpeed();
System.out.println("Variable value is "+tesla.maxSpeed);
}
}

The output of this program is

Maximum speed is 200
Variable value is 200

A constructor is a block of code that in initializes an object. Yup, that’s it.. It is called when the object of a class is created. It has the same name as the class and has no return type. Recall , when we were initializing the object of class Car;

Car tesla = new Car();

Car() was identified as the constructor but remember we never wrote any code for a constructor in the class Car, when this happens, Java compiler automatically build a constructor for us. A class can have more than one constructor.

The following shows a constructor

public class Car{
Car(){
}
}

There are two types of constructors; no-argument constructor and a parameterised constructor. Example code of both below;

// No argument constructor examplepublic class Car{
Car(){
System.out.println("This is a car");
}

public static void main(String [] args){
Car tesla = new Car();
}
}

The result of this code is;

This is a car

Another example

// Parameterized constructor examplepublic class Car{
Car(String name){
System.out.println("This is a "+name);
}

public static void main(String [] args){
Car tesla = new Car("Tesla Car");
}
}

This result

This is a Tesla Car

A constructor in Java is similar to a method without return type which means it can be overloaded. Constructor overloading is simply creating multiple constructors with different parameter lists. An example is

public class Car{
int id;
String name;
int speed;
//creating two arg constructor
Car(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Car(int i,String n,int a){
id = i;
name = n;
speed=a;
}
void display(){
System.out.println(id+” “+name+” “+speed);
}
public static void main(String args[]){
Car tesla = new Car(111,”TeslaX”);
Car tesla2 = new Car(222,”TeslaXX”,2500);
tesla.display();
tesla2.display();
}
}

The result of this code

111 TeslaX 0
222 TeslaXX 2500

I hope you found this insightful. Next off in the series is Nested classes and Access modifiers/Access specifiers.

Data Scientist/Software Developer.. Aspiring robotics engineer. Tech and Artificial Intelligence enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store