Object Oriented Programming concepts in java lionguest studios

Object Oriented Programming (OOPs) concepts in Java Part 1/2

An Object Oriented Programming (OOP) is one of the styles of writing robust, modular, reusable, and maintainable code. A programming style that revolves around objects knows as object oriented programming (OOP). It follows the principle of software engineering called DRY “Don’t Repeat Yourself” which helps in minimizing the repetition of code.

Let’s understand the object oriented programming concepts in java by combining it with a real word example.

Classes and Objects in Object Oriented Programming

Class in java allows us to define all the variables and methods at one place related to a particular entity. For example, Let’s say we want to build a car (in this case car is the entity) then for that we first have to create a blueprint or a design of that car and that will contain the car’s dimensions like width & height, car’s name, model no, car’s speed, braking system, auto or manual mode, etc. These are the things that we first have to figure out related to the car, and based on this data or blueprint we can create the actual physical car.

In OOP, the class is where we define all of such data and because of that class is also called a blueprint. The data which is stored inside a class is in a form of variables and methods. As just after creating a blueprint or a design of a car the physical car is not created, the same way whenever we define a class in java no object will be created which means no car will be created.

To create a car in java we first have to create an object of that class. Creating an object simply means allocating memory to the class which we have created. This is done with the help of a new keyword in Java. After allocating the memory, the object will now have all the data (variables and methods) which we have defined inside our class. Using this object, we can manipulate the data which is present inside that object. You can create as many car objects as you want from the Car class provide different properties to every object. Refer to the figure shown below which will provide you with a pictorial view of how the classes and objects work.

classes and objects pictorial view in java lionguest studios website
Classes and Objects pictorial view in Object Oriented Programming

The above image contains a Car class and using this class we are creating multiple car objects. This Car class contains two variables, company (the company who manufactured the car), speed (speed of the car) and lastly, we have a method called as getSpeed() which prints the speed of the car.

To create a physical car we first have to create an object of this class with the help of a new keyword in Java. So, here we have created 3 objects from this class, the first one represents the Honda Car which has a speed of 100 km/hr, the second object represents the Jeep car with a speed of 500 km/hr and the third object represents the BMW car with the speed of 800 km/hr.

The above example of the class and objects is representation in the code below.

import java.io.*;

 class MainClass {

        public static void main(String[] args) {   

            Car honda = new Car();     
            honda.company = "Honda";     
            honda.speed = 100;     
            honda.getSpeed();    
 
            Car jeep = new Car();     
            jeep.company = "Jeep";     
            jeep.speed = 500;     
            jeep.getSpeed();     

            Car bmw = new Car();     
            bmw.company = "BMW";     
            bmw.speed = 800;     
            bmw.getSpeed(); 
    }
}

 class Car{
     String company;
     int speed;

    void getSpeed(){ 
        System.out.println(company+" car's speed is "+ speed+ " Km/hr"); 
    }
 }
Output:
Honda car's speed is 100 Km/hr
Jeep car's speed is 500 Km/hr
BMW car's speed is 800 Km/hr

Don’t worry if you didn’t understand each and everything which is written inside the above code. As we move along, everything will make sense.

Constructor in Java

A constructor tells us how much space to allocate to an object in memory. Every class in java has a constructor inside it and this constructor is called the default constructor. This default constructor is created by java and will be used to allocate memory to the object. By default, while creating an object a default constructor will be called. The reason why java calls a default constructor is that the constructor knows how much memory will be required to create an object of that class. You can also create your own constructors and a class can support any number of constructors.

A job of a constructor is to allocate space in memory for an object and to initialize the variables at the time of object creation. A constructor is also called a member method because it is present inside the class, it has the same name as the class name and it is represented by round brackets ‘( )‘. A constructor will always have a public access modifier because it can be called from inside any class.

class Car{

    // This is a default constructor
    public Car(){
 
    }
}

Whenever you will create a class you will not see the above code for the default constructor. But it will be there and while compiling the code the java compiler will call this default constructor if the compiler doesn’t find any other constructor.

Now with the default constructor, you manually have to initialize your variables after the object is created which is quite hectic at times. For, example, as we have seen above, whenever we were creating the object of the Car class at that time we were assigned the company name and the speed to the Car object manually inside our code. But we can also initialize any of these parameters at the time of object creation. To achieve this you can create your own constructors. The advantage of creating your own constructor is that you can initialize any number of variables present inside the class at the time of object creation.

class Car{

    int speed;
    String engineType;

    // This is a default constructor
    public Car(){
 
    }

    // Creating your own constructors

    // Constructor which takes one parameter
    public Car(String speed){
          this.speed= speed;
    }

    // Constructor which takes two parameter
    public Car(int speed, String engineType){
         this.speed= speed;
         this.engineType = engineType;
    }

    // You can call any one of the above constructors 

}

Here, The constructor which you will be creating will look the exact same as the default constructor, the only difference is the parameters which it will take. You can create any number of constructors as you want but the only condition is that it should take different numbers of parameters.

Calling a constructor in Java

In order to create an object, we use a new keyword in Java. By using this keyword Java compiler understands that you want to create an object. But just using the new keyword will not create an object for you as you also need to know how much space you need in memory to allocate for the object.

For that, you have to call the constructor. So, after the new keyword, you also have to write the constructor name (either the default constructor or the constructor which you have created) by passing appropriate parameters. This will call the constructor that will then tell the Java compiler how much space the object will require and the new keyword will allocate that much space and then the entire object will be stored inside a variable.

Below diagram illustrates this process.

working of constructors in java lionguest studios
Working of constructors in Java

Here, our aim is to simply create a Mercedes physical car using the Car class (blueprint). For that, we first need to know how much space we will need to store our Mercedes car object in memory (this is nothing but creating a physical car in the real world). To get the space needed to store the object we have to call the Car constructor. In this case, we are calling the Car constructor which we have created that only takes a single parameter called speed. Since we want to initialize the speed variable at the time of object creation we will call the constructor which we have created and pass in the value 100 which represents speed to the constructor.

After that, the new keyword will allocate that much amount of space to the object. This will create our Mercedes car object. Now to access this object we first have to store it in a variable and the name of that variable can be anything, here we have given mercedes as the variable name. This variable will be of type Car because the type of the object which we are storing inside this variable is also Car. So they both (object and variable) must be of compatible types.

import java.io.*;

class MainClass {

    public static void main(String[] args) {       
 
      // Calling our custom constructor & Creating the object      
      Car mercedes = new Car(100);     
        mercedes.company = "Mercedes-Benz";     
         mercedes.getSpeed(); 
     }
 }

 class Car{
     String company;
     int speed;

     // Creating our own custom constructor 
    // which takes speed as a parameter 
    public Car(int speed){     
    this.speed = speed; 
    } 

    void getSpeed(){      
    System.out.println(company+" car's speed is "+ speed+ " Km/hr"); 
    } 
}
Output:
Mercedes-Benz car's speed is 100 Km/hr

Keys points to remember about a Constructor in object oriented programming

  1. A constructor is a member method.
  2. It has the same name as the class name.
  3. It will never return anything.
  4. It tells us how much space in memory needs to be allocated for an object.

Keywords used in object oriented programming

Since the Java programming language follows the object oriented programming style of writing code, it supports various keywords like static, this, super, final, which can make our life much easier in writing and maintaining our Java code and while working with object oriented programming style. These Java keywords are explained in detail below.

Static Keyword in Java

Whenever you want to call any method in java we first have to create an object of that method and then only we can call that method. Now when will the object be created? When your program execution will start. From where the program execution starts in java? From the main method, Right. But here is a catch, main() is also a method itself, Right? Yes, then who creates an object of the main() method? The answer is no one creates an object of the main() method.

But we have seen that to call a method we have to create an object of that method and here we are saying we don’t create an object of the main() method. Here, the problem is main() is the starting point from where our program execution will start, so before starting the program execution how can we can an object which is not possible. This is a deadlock condition.

Object Oriented Programming in java static method dedlock condition
Deadlock condition in Java which can be solved using static keyword

To solve this deadlock, java provides us with a keyword called static. Using the static keyword you can directly call a method without creating an object in Java. That’s the reason why we use a static keyword before the main() method in our program. You can use this keyword not just for main() but for any method which you want to call without creating an object of it.

‘this’ keyword in Java

Whenever you have the same name for instance variable and for local variable then in that case we use this keyword. We have already seen this keyword in practice while we created our own constructor and passed the value of the speed variable at the time of object created.

class Car{
    // instance variable
    int speed;

    // speed variable inside the constructor is a local variable
     public Car(int speed){
         this.speed  = speed;
    }
}

Inside this class, we have declared a variable speed which is known as an instance variable. When we are creating our own constructor by passing in a variable speed as a parameter then this variable is called a local variable. Our aim here is to assign the value of local variable speed to the instance variable speed. Since both of these variables have the same name then how would you differentiate between them? This can be done with the help of this keyword.

Whenever we use this keyword on a variable it will tell the Java compiler that this variable is an instance variable and the value of the local variable needs to be assigned to this instance variable.

Super keyword in Java

The super keyword is present inside each and every constructor. You will not explicitly find the super() written inside the constructor but by default, it will be there. During inheritance, the super keyword will be used to call the default constructor of the parent class from the child class. If you want to call a constructor other than the default constructor of the parent class then you have to write the super keyword and pass in the parameters accordingly based on which constructor of the parent class you want to call from the child class.

import java.io.*;

 class Vehicle{
     public Vehicle(){ 

    } 

    public  Vehicle(int i){     
        System.out.println("You called a constructor with 1 parameter of Parent class.");     
    }
 }

 class Car extends Vehicle{
     public Car(){ 

    } 

    public Car(int i){     
        //This will call the second constructor of Vehicle class     
        super(i);     
        System.out.println("Calling vehicle class constructor"); }
     }

 public class MainClass{
     public static void main(String args[]){
         Car myCar = new Car(10);
     }
 }
Output:
You called a constructor with 1 parameter of Parent class. 
Calling vehicle class constructor

final keyword in Java

The final keyword can be used with a variable, method, or class.

final keyword with variable

Whenever you want to keep the value of the variable constant throughout the execution of the program then in that case you can use the final keyword. For example, every car will always be having 4 wheels. No matter what happens this value will never change. So what we can do is we can make the wheels variable as final in our program and give it a value of 4. Now, this value will remain the same you cannot change it later.

final int wheels = 4;

final keyword with a class

Now let’s see why we even need to make our class as final. Let’s say, we have 3 classes, first is the Main class, second is the Car class (child class) and third is the Vehicle class (It is a parent class. The vehicles can represent cars, bikes, trucks, etc).

The Vehicle class has a method called accelerate() using which our vehicles will move. Our Car class also wants to implement such a method so that our cars can move. But implementing the same thing again which is already present is not a good idea. So, in java, there is something called inheritance using which we can inherit the properties of the other class and access them inside our own class. This is done with the help of the extend keyword.

import java.io.*;

class Vehicle{
    void accelerate(){
        System.out.println("move...");
    }
}

class Car extends Vehicle{
    
}

public class MainClass{
    public static void main(String args[]){
        Car myCar = new Car();
        myCar.accelerate();
    }
}
Output:
move...

In the above code, notice that after creating an object of the Car class even though the accelerate() method is not present inside the Car class still, we are able to access it with the help of inheritance. Now to avoid using any methods or variables of a class by another class (i.e to disable inheritance) we can make that class has final. In this case, we will make the Vehicle class final using the final keyword.

final class Vehicle{
    void accelerate(){
        System.out.println("move...");
    }
}

Now no other class will be able to access the methods of this class.

final keyword with a method

We will take the same example which we have used for understanding the final keyword with class, but this time we will have another accelerate() method inside our Car class as well.

import java.io.*;

class Vehicle{
    void accelerate(){
        System.out.println("move...");
    }
}

class Car extends Vehicle{
    void accelerate(){
        System.out.println("move my car...");
    }
}

public class MainClass{
    public static void main(String args[]){
        Car myCar = new Car();
        myCar.accelerate();
    }
}
Output:
move my car...

In this case, we are overriding the accelerate() method inside our Car class. The overriding a method simply means that the method is already present inside a parent class (in this case Vehicle class) and then you are also creating a method with the same name and signature inside the child class (in this case Car class). In this way, you can override the contents inside the accelerate() method of the parent class with the accelerate() method of the child class. To avoid this we can make the method present inside the Vehicle class (parent class) as final so that no other class can override its methods.

class Vehicle{
    final void accelerate(){
        System.out.println("move...");
    }
}

That’s all for this blog post. In the upcoming blogs of the object oriented programming series in Java, we will see the 4 object oriented paradigms i.e Polymorphism, Inheritance, Encapsulation, and Abstraction of the object oriented programming concepts in java.

Thanks for the read. If you like the content then support us on Patreon. Your support will surely help us in writing more of such content.

To read more such blogs about Object oriented programming related stuff visit our blogs page on LionGuest Studios.

Leave a Comment

Your email address will not be published. Required fields are marked *