JavaObject-oriented programmingClasses and objects

Objects

4 seconds read

A typical object-oriented program consists of a set of interacting objects. Each object has its own state separated from others. Each object is an instance of a particular class (type) that defines common properties and possible behavior for its objects.

All classes from the standard library (String, Date) and classes defined by programmers are reference types that mean variables of these types store addresses where the actual objects are located. In this regard, the comparison and assignment operations work with objects differently than with primitive types.

Creating objects

The keyword new creates an object of a particular class. Here we create a standard string and assign it to the variable str:

String str = new String("hello");

The variable str stores a reference to the object "hello" located somewhere in the heap memory.

In the same way, we can create an object of any class we know.

Here is a class that describes a patient in a hospital information system:

class Patient {
    String name;
    int age;
}

Here is an instance of this class:

Patient patient = new Patient();

Despite the fact, that String is a standard class and Patient is our own class, both classes are regular reference types. But they have one big different discussed below.

Immutability of objects

There is an important concept called immutability. It means that an object always stores the same values. If we need to modify these values, we should create a new object. The common example is the standard String class which is immutable and all operations produce a new string. Immutable types allow you to write programs with fewer errors.

The class Patient is not immutable because it is possible to change any field of an object.

Patient patient = new Patient();

patient.name = "Marry";
patient.name = "Alice";

In the following topics, we will look at the existing immutable classes as well as learn how to create new ones and when to use them.

Sharing references

More than one variable can refer to the same object.

Patient patient = new Patient();

patient.name = "Marry";
patient.age = 24;

System.out.println(patient.name + " " + patient.age); // Marry 24

Patient p = patient;

System.out.println(p.name + " " + p.age); // Marry 24

It is important to understand that two variables refer to the same data in memory rather than two independent copies. Since our class is mutable, we can modify the object using both references.
patient.age = 25;
System.out.println(p.age); // 25


Nullability

As for any reference types, a variable of a class-type can refer be null that means it is not initialized yet.

Patient patient = null;

This is a common feature in Java available for classes since they are reference types.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo