Java OOP Guide: Objects

  • Hello Jetto Net followers!

    Welcome to the second part of our Java Object Oriented Programming (OOP) series. In the previous article, we examined classes, the basic building block of OOP, in detail. In this article, we will discuss “objects” which are concrete examples of classes.

    What is an Object?

    Objects are the real-world representatives of classes. While a class defines how an object should be, an object is a living example of this definition. For example, the “Car” class defines the characteristics (make, model, year, color) and behaviors (acceleration, deceleration) that a car object should have. Each car generated from this class (for example, a red Ferrari, a blue BMW) is an object.

    How to Create an Object?

    To create an object in Java, we use the new keyword. The new keyword is followed by the name of the class of the object we want to create and parentheses (). Inside the parentheses, we can give parameters to the constructor method of the object.

    Code
    Car myCar = new Car(); 

    In this example, we created an object from the Car class called myCar. This object will have all the properties and behaviors of the Car class.

    Access to Properties of an Object

    To use the behavior of an object, we use the dot (.) operator. The dot operator is followed by the name of the behavior (method) we want to use and parentheses.

    Code
    myCar.accelerate(); // Output: The car is accelerating!
    myCar.slow(); // Output: The car is slowing down!

    In this example, we call the accelerate() and slow() methods of the myCar object.

    Storing Objects in Memory

    Objects are stored in a memory region in Java called the heap. When we create an object, we actually allocate space on the heap for that object and create a reference to the object. The reference holds the address of the object on the heap.

    Garbage Collection

    Java has an automatic garbage collection mechanism to prevent unused objects from taking up memory space. The garbage collector periodically cleans the heap of unused objects.

    Importance of Objects

    Objects are the basic building blocks of OOP. Thanks to objects:

    • We can model real-world objects.
    • We can make our code more organized, understandable and reusable.
    • We can decompose complex systems into simpler parts.

    In the next installment, we will continue to explore other important concepts of OOP. If you have any questions, let me know in the comments.

    Happy coding!

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!