Object-Oriented Programming: Objects

Objects are a central concept in Object-Oriented Programming (OOP). In this article, you will learn what objects are in OOP and how to use them.

From the previous lesson, we learned that “In Object-Oriented Programming, we use classes to represent concepts of the real world.”.

In other words, a class is used to represent a type of object from the real world. For instance, we can use a class to represent all the vehicles of the real world, or the people, etc.

So, we already know how to represent a type of object but, how we represent or handle a specific object?

Representing specific objects

Let’s describe better what we want to do. Consider the example of the previous lesson.

” Lenovo is a PC company that creates and sells laptops. The company has a record of all the laptops that the company creates with the following information: model, (screen) size, price. (…)” (complete example here) and the class laptop we designed in Java.

class Laptop{
    private int screenSize;
    private float price;
    
    Laptop(int size, float price){
        this.screenSize = size;
        this.price = price;
    }
}

Using the previous class, we can model all laptops that are in the company. But how do I refer to a specific laptop? For instance, the laptop that has 15 inches as screen size and the price is 500 USD?

To represent a specific object from the real world, we use the concept object from OOP.

Formally, in OOP an object is an instance of a class.

Do not confuse the two concepts of objects although they represent the same. One is the object from real-life, the pen you have in your hands, the laptop you are using to read, your phone; the other one, is the representation of that object in a Programming Language, using the OOP paradigm.

Creating objects in Java

To create an object in Java, we must use the keyword new in the following way.

Laptop myLaptop = new Laptop(15,500);

With the previous line of code, we created a Laptop object (myLaptop). This object represents a specific laptop, one that has 15 inches of screen and the price is 500 USD.

But how it works? How will the programming language know the screen is 15 inches and the price is 500 USD?

Remember the concept constructor from the previous lesson? That’s how. In the constructor, we specified that we have to use two values when we use this class to create an object, the values are “int size, float price “. Also, remember about this: ” It is used to initialise the values of the attributes.”

Classes are also informally called templates to create objects. It is considered in that way because we define in the class what are the attributes and operations that any object (created using the class) will have.

Using objects in Java

Now that we have the object myLaptop, how can we use it?

We use objects through the class methods (operations defined in the class).

From the previous lesson, we have the following class implementation.

class Laptop{
    private int screenSize;
    private float price;

    Laptop(int size, float price){
        this.screenSize = size;
        this.price = price;
    }

    public float getVAT(){
        return this.price * 15 / 100;
    }
}

Methods without parameters

Because we implemented a method named getVAT, we can use this method through the object we now have. The way we do it is as follows:

myLaptop.getVAT()

AS you can see from the previous example, we write the name of the object, then ‘.’, and after that, we write the method name (or operation name) as defined in the class. Because the method does not receive any parameter, we write empty parenthesis after the method name.

Let’s say we want to print the vat on the screen. We can do it in two ways, we create a new variable to store the value of the VAT and print the value on that new variable. The second way is to print straight the value that the method getVAT returns. See the examples below.

First way

float vat = myLaptop.getVAT();
System.out.println(vat);

Notice that the type of variable vat must be the same (or compatible) with the type of the value that the method returns. If you check the class implementation, you will see that the method returns a float value. That’s why the type of the variable vat is float.

Second way

System.out.println(myLaptop.getVAT());

This is a more straightforward way to print values returned by a method. It is more concise and avoids the declaration of a new variable.

In other words, this way is the recommended one.

Methods with parameters

To continue with the previous example, let’s suppose we want to know if the laptop is cheaper than a certain price. This type of operation can help us when we have a budget to consider.

Imagine you going to shop and asking, do you have a laptop that costs 300 USD or less?

We can implement a method that answers this question in the following way:

public boolean PriceEqualOrLessThan(float price){
    if (this.price < price)
        return true;
    else
        return false;
}

What is different in the previous method compared to the method getVAT?

Yes, you are right, the parameters.

But why this method has a parameter (float price)?

Well, remember that we use parameters when we need extra data to carry on certain operations. In this case, we want to answer, “if the laptop is cheaper than a certain price“.

As one example, we can answer if the laptop costs less than 300. But we can also answer in the same way if the laptop costs less than 600, or 100, or any price.

Because we don’t know beforehand what price we want to compare, we use a parameter. Using a parameter, you can ask the same question for several prices, using the same method. One hint that can tell you need to use a parameter is the way we wrote the problem: “if the laptop is cheaper than a certain price“. Certain price is not specific, it can vary, here we should realize we need to use one parameter for the “certain price”.

Notice that when we define a parameter in a method, we have to specify the type, float in this case, because we already know that a price is a real number.

For now, don’t worry about the keywords if and else. Those you can understand intuitively by using the meaning of the English words. In a later article, I’m going to explain in detail all you can do with this type of instruction.

Did you see the name of the method? It is PriceEqualOrLessThan.

Why I write it like that?

Well, methods and variable names should be intuitive. Just by reading the code, you should understand what the variable of the method can be used for. If you read this method name, you will get a pretty good idea of what the method can do.

On another hand, every time a new word start, we use uppercase. This is known as camel case notation. It is used to make the code more readable.

Just compare by yourself and answer which one you understand better:

  • PriceEqualOrLessThan
  • priceequalorlessthan

Why is important that your code is readable?

You probably will have to read your code several times. Even if you wrote the code yourself, the next time you read it you might not understand what you wrote.

Also, in software development, you should contribute to a project. So, your code will be used by another programmer/coder, therefore the need for others to understand your code.

How to use a method with parameters in Java

The way we use a method with parameters is as follow:

boolean exists = myLaptop.priceEqualOrLessThan(300);

Notice that we create a variable of type boolean to store the result of the method. Again, we have to do it like that because the method returns a boolean according to the method definition.

We return a boolean from the method because we have only two possible answers: yes (true) or not (false). The laptop price is equal to or less than a certain price. The type more suitable to store only two possible values is the type boolean.

An important fact to notice is that when we invoke the operation/method priceEqualOrLessThan, the parameter is just a number (it can also be a variable). So, here we don’t specify the type of the value we are passing as a parameter.

We specify the type of the parameter only on the method definition (within the class).

Laptop class implementation of the example

class Laptop{
    private int screenSize;
    private float price;

    Laptop(int size, float price){
        this.screenSize = size;
        this.price = price;
    }

    public float getVAT(){
        return this.price * 15 / 100;
    }

    public boolean priceEqualOrLessThan(float price){
        if (this.price < price)
            return true;
        else
            return false;
    }
}

Java Console application for the laptop example

public class Main {
    public static void main(String[] args) {
   // write your code here
        Laptop myLaptop = new Laptop(15,500);

        float vat = myLaptop.getVAT();
        System.out.println(vat);
        
        System.out.println(myLaptop.getVAT());

        boolean exists = myLaptop.priceEqualOrLessThan(300);
    }
}

Summary

In this article, we discussed how to use objects.

The main concepts we discussed are:

  • Object: an instance of a class
  • Class: a template to create objects (informal definition).
  • Parameter: additional values we need in some methods to perform a certain operation.
  • Methods without parameters
  • A method with parameters: when we define parameters, we have to specify the type of the parameter.
  • Using objects to perform operations. If the operation/method we want to use receive a parameter, we write the value we want to pass a parameter without the type definition.

H@ppy coding!