OOP approach in Java

OOP approach in Java

OOP approach in Java: Constructors

In my previous article on object-oriented programming, we managed to decipher that a class is like a blueprint that represents real-life objects. Just like real-life objects, classes have states and behaviors. By default, classes are package-private, but you can assign any access modification depending on the nature of the class and how it interacts with the whole system. To create a class, you need an access modifier, the “class” keyword, the name of the class, if it is inheriting or interfacing with any other class, followed by either implement or extend, and the name of the parent class or interface.

Now, a class that was just created has no use if there are no instances of the class to access methods or variables. To come to life, classes require a special type of method called a constructor to initialize the methods and variables in that class. Initialization is defined as giving the first (initial) value or a default value (int age = 0). Constructors are the key to creating an object that is an instance or reflection of a class. They aid in the discovery and retrieval of methods and parameters declared in an instance of a class.

Constructors are like any method having access modifiers, but differ in that they carry the name of the class and do not have a return type since ideally they return the instance of the class. By default, if there are no specific declarations of a constructor type, the no-argument constructor is provided. Once a constructor is created, the default no-args constructor is no longer available, so if one needs to use it, there is a need for an explicit declaration. A class can have multiple constructors, they can be overloaded and reused by other constructors. Using the previous method of a driverless car moving from point A to point B:

No alt text provided for this image
Constructor method with two arguements of String type

The Driverless Route method on line 10 shows a constructor that uses two arguments: the departure location and the destination. The highlighted area in blue has the assignment of class variables departureLocation and destinationLocation to the arguments in the DriverlessRoute constructor method. The “this” keyword will tell the compiler to refer to the class variable; otherwise, it will refer to the arguments.

No alt text provided for this image
Creating a new object and calling a class method endTrip


In this instance, on line 4, we are creating a new object, which is a trip from Harare to Gweru, using the “new” keyword followed by the constructor method. This trip has two arguments that are required to satisfy the creation of any instance of an object of type DriverlessRoute. On line 8, we can now access the endTrip method, which is in the class DriverlessRoute.

Overloading Constructors

Earlier, we talked about how one class can have multiple constructors. This helps with easier logic sharing, as shown below.

On line 9 we have the first consuctor, which initializes the model field as the only argument. On line 13, the second constructor overloads the first constructor and upholds the logic where the id is an argument and initializes departure and destination as additional arguments. This is the same logic as the third constructor, which calls the second constructor and further initializes the departureTime and bestRoute.?

To call a constructor from another constructor, you use the “this” keyword and the arguments of the constructor being called, as shown on lines 14 and 28. The constructor that is being overloaded NEEDS to be the first line in the constructor body of the constructor calling it. This helps with the order of execution. Remember, for us to create a new instance of the class, we call the constructor as follows:

public class Main {
    public static void main(String[] args) {

    DriverlessRoute driverlessRoute = new DriverlessRoute(
            "e58ed763-928c-4155-bee9-fdbaaadc15f3",
            "Harare",
            "Gweru",
            LocalDateTime.now(),
            Collections.singletonList("Harare,
                                      Chegutu,
                                      Kadoma,
                                      Kwekwe,
                                      Gweru"));
    {
        driverlessRoute.endTrip();
    }

    }
}        

This will be the third constructor. Just because the first execution is calling the second constructor, it moves to the second, and since the second first refers to the initial constructor, the compiler will now set the UUID. From there, the other arguments should be satisfied with the second constructor and, lastly, with the independent execution of the third. The compiler will separate all the overloading constructors using the number of arguments and the types of arguments. For example:?

The difference between the first and second constructors is that, although they share the same name, the first constructor only has one parameter as an argument of type String. The second has two more arguments, and the third not only has an extra number of arguments, but they are of different types. If the number of arguments and argument type are similar, it causes a compilation error.

I took the liberty of explaining it in this way:

No alt text provided for this image


要查看或添加评论,请登录

Hazel T Chikara的更多文章

社区洞察

其他会员也浏览了