Thumbnail image

Object-oriented programming (OOP) Part 1

3/1/2024 7-minute read

Part 1: Overall definition.

Object-oriented programming (OOP) is a programming paradigm that organizes code into reusable and modular units called objects. Each object contains data, or attributes, and behavior, or methods, that operate on that data.

OOP is based on the idea of encapsulation, where objects encapsulate their state and behavior, and information hiding, where an object’s internal details are hidden from other objects. This helps to reduce complexity and increase the modularity and maintainability of code.

In OOP, objects interact with each other by sending messages or calling each other’s methods. Inheritance allows objects to inherit properties and behavior from other objects, which can help reduce code duplication and increase code reuse. Polymorphism allows objects to take on multiple forms and behave differently depending on the context in which they are used.

Overall, OOP is a powerful programming paradigm that can help developers create complex, scalable, and maintainable software systems. Classes are the building blocks of programs built using the object-oriented methodology. Such programs consist of independent self-managing modules and their interactions. An object is an instance of a module, and a class is its definition.

Just to make it clear, this series of articles is to help me prepare for technical interviews. However, I know it may also be helpful for other developers, which is why I will be sharing my notes.

In the real world, objects like cars, buildings, and humans have states and behavior. For instance, a Car has a name, speed, and fuel, and can refuel, drive, and park.

In Java, classes allow developers to create their own user-defined data types with multiple variables and functions. Classes help compartmentalize an application’s code into different components, making it easier to maintain and update them.

Below we can see the state of a car object in java:

    public class Car {

        //   FIELDS
        private int topSpeed;
        private int totalSeats;
        private int fuelCapacity;
        private String manufacturer;
    
        //   METHODS
        void refuel() {}
        void park() {}
        void drive() {}
    }

Benefits of using classes

The concept of classes allows us to create complex objects and applications in Java. This is why classes are the basic building blocks behind all of the OOP’s principles.

Fields

These are also known as the member variables of a class. This is because they contain the information relevant to the object of the class. A car object would have a top speed, a certain number of seats, and so many other pieces of data that we could store in variables.

Methods

This category of attributes enables the class object to perform operations using the fields. In the case of the car class, the refuel() function would fill up the fuelCapacity property of the object.

Access modifiers

Private

A private member cannot be accessed directly from outside the class. The aim is to keep it hidden from the users and other classes. It is a popular practice to keep the data members private since we do not want anyone manipulating our data directly. We can make members private using the keyword private.

Public

This tag indicates that the members can be directly accessed by anything which is in the same scope as the class object. Member functions are usually public as they provide the interface through which the application can communicate with our private members.

    Cop c = new Cop(); // Object created
    c.getGun(); // Can access the gun
    c.gun = 0; // This would cause an error since gun is private

Protected

The protected category is unique. The access level to the protected members lies somewhere between private and public. The primary use of the protected tag can be found when using inheritance, which is the process of creating classes out of other classes.

The protected data members can be accessed inside a Java package. However, outside the package, they can only be referred to through an inherited class.

Default

If we do not mention any access modifier, then it is considered to be default access. The default access is similar to the protected. It also has package-level access, but it also applies to inherited classes as well, unlike protected. So, you can say that its access is more limited.

Fields

Let’s talk more about the fields. Fields are data members inside a class.

Static fields

A static field resides in a class. All the objects we create will share this field and its value. Static fields reside in the class. We don’t need an instance of the class to access static fields. We can access the static fields of a class by just writing the class name before the field:

class Car {
  // static fields
  static int topSpeed = 100;
  static int maxCapacity = 4;  
}
    
class Demo {
  public static void main(String args[]){
    // Static fields are accessible in the main
    System.out.println(Car.topSpeed);
    System.out.println(Car.maxCapacity);   
  }
}

Non-static fields

Non-static fields are located in the instances of the class. Each instance of the class can have its own values for these fields.

    class Car {

      // Non-Static Fields
      int speed;
      int capacity;

    }

Final fields

A final field cannot have its value changed once it is assigned.

    class Car {
      // Final field of capacity = 4
      // Now Capacity can never be changed from 4
      // to some other value throught the program
      final int capacity = 4;
    
    }
Car class has capacity equals to 4 which can’t be changed. If you try to do so, you will get a compilation error.

The purpose of methods

Methods act as an interface between a program and the data fields of a class in the program.

These methods can either alter the content of the data fields or use their values to perform a certain computation. All the useful methods should be public, although, some methods which do not need to be accessed from the outside could be kept private.

Methods

A method is a group of statements that performs some operations and may or may not return a result.

Method parameters and return type

Method parameters make it possible to pass values to the method and return type makes it possible to get the value from the method. The parameters are declared inside the parentheses after the method name while the return type is declared before method name. Example of Methods in Java.

    class Car {
    
      // Public method to print speed
      public void printSpeed(int speed) {
        System.out.println("Speed: " + speed);
      }
    
    }
    
    class Demo {
    
      public static void main(String args[]) {
        Car car = new Car();
        car.printSpeed(100); // calling public method
      }
    
    }

Return statement

For methods that define a return type, the return statement must be immediately followed by return value.

    // public method with one parameter speed.
    public int printSpeed(int speed) {
      // ...
        
        
      return speed + 5; // return statement
    }

Getters and setters

These two types of methods are very popular in OOP. A get method retrieves the value of a particular data field, whereas a set method sets its value.

It is a common convention to write the name of the corresponding member fields with the get or set command.

Note: Must of IDEs can generate those methods automatic, but is a good practice in the beginning of study, write it by yourself.

Let’s write get and set methods for ‘speed’ in our Car class:

// Car class
    class Car {
    
      private int speed; // member field speed
        
      // Setter method to set the speed of the car
      public void setSpeed(int x) {
        speed = x;
      }

    // Getter method to get the speed of the car
      public int getSpeed() {
        return speed;
      }
    
    }
    
    class Demo {
    
      public static void main(String args[]) {
        Car car = new Car();
        car.setSpeed(100); // calling the setter method
        System.out.println(car.getSpeed()); // calling the getter method
      }
    
    }

Conclusion

In this article, we’ve introduced the basics of object-oriented programming (OOP) and discussed how classes can be used to create user-defined data types. We’ve also seen how classes can help compartmentalize code and make it easier to maintain different parts of an application.

To summarize, here are the key points:

OOP organizes code into reusable and modular units called objects, which contain data (attributes) and behavior (methods). Classes are used to create user-defined data types in Java and can contain multiple variables, pointers, and functions. Compartmentalizing code into classes makes it easier to maintain and modify different parts of an application. In the next part of this series, we will dive deeper into methods overloading and constructors. You can expect to learn:

How methods define behavior for objects and how they can be used to manipulate object data. How constructors are used to create objects from classes. We hope you found this article helpful!

If you have any comments or questions, feel free to leave them below. Stay tuned for the next part of the series.

Posts in this Series