JavaObjects in Java: The Basics

Objects in Java: The Basics

Java programming tutorial

During the last twenty-plus years, Java has made quite a name for itself as a tremendously powerful object-oriented programming (OOP) language. But what does “object-oriented” really mean? Is it safe to assume that objects are represented in much the same way across all OOP languages? As we will see shortly, objects in Java are far more than mere containers for complex data. In this tutorial, we will delve into the concept of objects in Java, exploring what they are, how they work, and their significance in Java programming.

What are Java Objects

In Java, an object is a fundamental unit of a program, representing a real-world entity or concept. It combines data (also referred to as attributes) and behaviors (also known as methods) into a single entity. Objects are concrete instances of classes, which act as blueprints or templates for creating objects. As such, the class defines the structure and behavior that its instances (objects) will have. The class encapsulates data (in the form of fields or variables) and behavior (in the form of methods or functions).

You can learn more about classes in our tutorial: Overview of Java Classes.

Real-world Parallels

In our daily lives, we constantly interact with objects. Java objects mirror these real-world counterparts. Consider a bank account – it possesses a unique identifier (account number), data (account type, balance, etc.), and a set of behaviors (deposit, withdraw, transfer, and so on). Objects are not limited to inanimate objects; a concept such as a task can also be represented as an object. Finally, living things such as animals and people are often represented by objects in Java programs. Here are a few examples describing some objects’ class (blueprint), attributes (data) and methods (actions):

  • Person
    • Class: Person
    • Attributes: name (String), age (int), address (String)
    • Methods: sayHello(), getAge(), setAddress()
  • Car
    • Class: Car
    • Attributes: make (String), model (String), year (int), vin (String)
    • Methods: start(), accelerate(int speed), stop()
  • Bank Account
    • Class: BankAccount
    • Attributes: accountNumber (String), balance (double), owner (Person)
    • Methods: deposit(double amount), withdraw(double amount), getBalance()
  • Book
    • Class: Book
    • Attributes: title (String), author (String), ISBN (String), numPages (int)
    • Methods: open(), close(), turnPage()
  • Circle
    • Class: Circle
    • Attributes: radius (double)
    • Methods: calculateArea(), calculateCircumference()
  • Task
    • Class: Task
    • Attributes: title (String), description (String), isCompleted (boolean)
    • Methods: start(), update(), markAsCompleted()

How to Create Objects in Java

As mentioned previously, a class in Java serves as a blueprint for creating objects. It defines the structure and behavior that its instances (objects) will have. The class encapsulates data (in the form of fields or variables) and behavior (in the form of methods or functions). To use a class, you create objects of that class. This process is known as instantiation. It involves allocating memory for an object and returning a reference to it. The new keyword is used to create objects in Java.

For instance, suppose that we have the following BankAccount class:

class BankAccount {
    private double balance;  // Private field
    
    public void deposit(double amount) {
        // Deposit logic
    }
    
    public double getBalance() {
        return balance;
    }
}

We would now instantiate an object instance by using the new keyword as follows:

BankAccount savingsAccount = new BankAccount();

In the above code example, we are also assigning the object to a variable so that we can refer to it later on in the program. We could also also access its fields and methods directly by enclosing the instantiation statement in parentheses:

if ( (new BankAccount()).getBalance() == 0.00d ) {
  // promotion in effect
} else {
 // no promotion at this time
}

Characteristics of Objects in Java

Java Objects share a few characteristics with those of other object-oriented languages. These help promote code reusability, reduce costs, reduce time, and make it easier for developers to build complex applications. These include:

  • Encapsulation
  • Inheritance
  • Polymorphism

Encapsulation

Encapsulation is the practice of bundling data (fields) and methods that operate on the data within a single unit, i.e., a class. It protects the data from being accessed or modified by external entities directly.

In this example, balance is encapsulated, and it can only be accessed or modified through the public methods deposit() and getBalance():

class BankAccount {
    private double balance;  // Private field
    
    public void deposit(double amount) {
        // Deposit logic
    }
    
    public double getBalance() {
        return balance;
    }
}

You can learn more about encapsulation in our tutorial: What is Encapsulation?

Inheritance

Inheritance allows one class (subclass) to inherit the attributes and methods of another class (superclass). It facilitates code reuse and the creation of specialized classes based on existing ones.

class Vehicle {
    void start() {
        System.out.println("Vehicle started");
    }
}

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

In the above code example, Car inherits the start() method from Vehicle and adds its own accelerate() method.

You can learn more about inheritance in our tutorial: What is Inheritance?

Polymorphism

Polymorphism allows objects to take on multiple forms. In Java, this is achieved through method overriding (where a subclass provides a specific implementation of a method defined in its superclass) and method overloading (where multiple methods with the same name but different parameters coexist).

class Shape {
    void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }
    
    void draw(int radius) {
        System.out.println("Drawing a circle with radius " + radius);
    }
}

In the above Java example, Circle overrides the draw() method from Shape and also overloads it with a version that takes a radius parameter.

You can learn more about Polymorphism in our guide: What is Polymorphism?

Objects and Memory Management in Java

One of the great things about Java is that it manages memory automatically through a process called garbage collection. When an object is no longer reachable (i.e., there are no references to it), it becomes eligible for garbage collection, and the memory it occupied is reclaimed. That being said, it doesn’t mean that developers need not concern themselves with memory management; we can inform the Java Virtual Machine (JVM) that an object is no longer required by explicitly setting any references to it to null. In the following example, the person1 variable no longer references the object, so it can be garbage collected:

Person person1 = new Person();  // Creating an object
person1 = null;  // Making the object eligible for garbage collection

Final Thoughts on Objects in Java

Objects lie at the core of Java programming. They encapsulate data and behavior, allowing for modular and organized code. By fully understanding objects in Java, developers are better equipped to create efficient, modular, and maintainable code.

You can learn more about object-oriented programming in our tutorial: Object-oriented Programming in Java.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories