Java Class and Object

One of the key features of Java is its support for Object-Oriented Programming (OOP), which is based on the concepts of classes and objects. In this tutorial, we will discuss what a Java class and object are and how they are related.

Java Class

In Java, a class is a blueprint or template that defines the properties and behaviors of an object. It is a user-defined data type that encapsulates data and methods. A class can have data members (variables) and member functions (methods), which can be accessed by creating an instance of the class (an object). The general syntax for declaring a class in Java is as follows:

class ClassName {
    // data members (variables)
    // member functions (methods)

Let’s look at an example of a simple Java class:

class Person {
    String name;
    int age;
    void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");

In this example, we have defined a class called “Person” that has two data members (variables) – “name” and “age” – and one member function (method) – “sayHello()”. The “sayHello()” method simply prints out a greeting message that includes the name and age of the person.

Java Object

An object is an instance of a class. It is created using the “new” keyword and its constructor. Once an object is created, it can access the data members and member functions of its class. In other words, an object is a specific realization of a class. Here is an example of how to create an object of the “Person” class:

Person john = new Person();

In this example, we have created an object called “john” of the “Person” class using the “new” keyword and its constructor. Once the object is created, we can access its data members and member functions using the dot (.) operator. For example, we can set the name and age of the person using the following code: = "John";
john.age = 25;

We can also call the “sayHello()” method of the “john” object using the following code:


This will output the following message:

Hello, my name is John and I am 25 years old.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author