Learn Java

Classes and Objects in Java

Java is an object-oriented programming language, which means it follows the principles of object-oriented programming (OOP). OOP is akin to the work of an architect: as an architect, you create templates called classes and build individual instances of these classes, known as objects. These core concepts of classes and objects are foundational to how Java and many other object-oriented languages are structured, allowing developers to model real-world entities and relationships in their code efficiently.

When programmers are writing a real program, they use standard classes as building blocks. However, they often need to declare new program-specific classes to better represent the domain area. In this topic, we will see how you can create a custom class in Java.

Declaring new classes

A new class is declared with the class keyword followed by the name of the class. For example, this is how you would create a class named Nothing:

class Nothing {
    // empty body
}

A class body can include fields, methods, and constructors. Fields store data, methods define behavior and constructors allow us to create and initialize new objects of the class. Not all Java classes have fields and methods so sometimes you will see classes without them.

The source code of a class is placed in a .java file. Usually, a source code file contains only one class and has the same name as that class, but sometimes a file can contain more classes.

Writing fields

field is a variable that stores data. It may have any type, including primitive types (int, float, boolean and so on) and classes (even the same class). A class can have as many fields as you need.

Let's declare a class called Patient:

/*
 *The class is a "blueprint" for patients 
 */ 
 class Patient {

    String name; 
    int age; 
    float height;
}

This class represents a patient in a hospital information system. It has three fields for storing important information about the patient: nameage, and height. All objects of the class Patient have the same fields, but their values may be different for each object.

Creating objects

Let's create an instance of the Patient class using the new keyword:

Patient patient = new Patient(); 

When you create a new object, each field is initialized with the default value of the corresponding type.

System.out.println(patient.name); // it prints null
System.out.println(patient.age); // it prints 0

Creating multiple objects of the same class

The following program creates two objects of the Patient class and prints the information about them:

public class PatientDemo {
    
    public static void main(String[] args) {
        
        Patient john = new Patient();
        
        john.name = "John";
        john.age = 30;
        john.height = 180;
        
        System.out.println(john.name + " " + john.age + " " + john.height);
            
        Patient alice = new Patient();

        alice.name = "Alice";
        alice.age = 22;
        alice.height = 165;
        
        System.out.println(alice.name + " " + alice.age + " " + alice.height);
    }
}

class Patient {

    String name;
    int age;
    float height;
}

Note that both classes are placed in the same file named PatientDemo.java. If we place two or more classes in the same .java file, only one of them can be declared as public, and the name of the .java file must match the public class in the .java file.

In the code above, we've created two patients — John and Alice, defined the values of their fields and then printed out the information about them. So, the output of the code above is:

John 30 180.0
Alice 22 165.0

Summary

In this article, we explored the fundamental concepts of creating classes in Java, which are essential for structuring programs within an object-oriented programming system. Custom classes are powerful tools because they allow you to define fields and methods that suit your specific use-case, enabling you to model real-world concepts effectively. Fields store the current state (data) of the class instances, and their values can differ between objects. By creating objects from a class, assigning values to their fields, and using them in your programs, you can manage complexity and enhance code reusability.

By applying object-oriented principles, such as encapsulation and abstraction, Java provides a robust way to write flexible and reusable code. Understanding these fundamental concepts and how to declare and work with classes is foundational to programming in Java. All in all, classes are a very powerful tool and we hope that you'll use them in your projects!

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate