What is Object and Class In Java?

Introduction

In this post, we will learn about Object and Class in Java. These topics form the core concepts and the building blocks of Object-Oriented Programming for a beginner.
As Java is an Object-Oriented Programming language, we design our program and represent/store key entities using Objects and classes.

What is Class In Java?

class is a blueprint/template that defines the state and behavior of objects. It is the logical entity that wraps all our code into a single unit and structures the code. In Java, we cannot compile our code without a class. Hence, we must write the code only within the class body surrounded by Curly braces.

The unique characteristic of a class is that a user can define their data members (Variables with Data Types) and methods, and we can access them by creating instances of the class.

Declaration Syntax: In java, we declare the class following this syntax:

How to Create a Class In Java : Example

Let us look at how a class looks like in a program.

Note: We can also declare a class with empty body i.e. with no data members and methods.

Let’s create a simple class:

Below given diagram explains the structure of class:Class Structure

What is an Object In Java?

An entity that has a state and behavior is known as an Object. In java, an Object is an instance of a class. Objects are created during runtime based on the blueprint/template that a class provides.

It is crucial to create objects; without them, we cannot access our program’s class members and methods. An object typically has three characteristics:

  • State: It represents the value of the Object.
  • Behavior: It means the behavior (functionality) of an object.
  • Identity: Java assigns a unique ID for each Object. The value of the ID is not visible to the external user.

Example: For the Employee class, each Employee object will have a state with name, age, and department, and behavior such as working on the assignment.

Declaration Syntax: 

How to Create an Object In Java : Example

In Java, we use the new keyword to create an object to allocate memory dynamically as Objects are stored in heap memory. Now, let us create an object of the class Employee.

When above statement gets called, physical object is created in the memory as below:

Object creation 1

How to Create Multiple Objects for Same Class

Now let’s create multiple objects for class Employee i.e. employee1 and employe2 and set the name and age for these two objects by accessing the members through object name.

Then we create the objects and set the values.

These two objects will be created in memory as below:

Object creation 2

X Ways to initialize object in java

There are many ways to initialize objects in java. We will look at each in detail.

1. Using Object Name

We can initialize the object and assign value to the data members using the Object or Reference name and the dot operator as we did in the above example while creating multiple objects. Let us look at the whole program.

Output:

Note: We can access the members directly with Object name only if there are no Access Modifiers in the Employee class such as private.

2. Using Method

Instead of initializing the data members using object names, we can create a method inside the Employee Class that will assign values to the members of that object. We can pass the values while calling the method to initiate the object.
This is a convenient approach when using multiple objects because we don’t have to assign values using the object names individually.

Let us look at the example.

We call initialize method for each object we create and then display the values.

Output:

3. Using Constructors

We can initialize Objects using constructors, an internal feature provided by Java to instantiate objects.

4. Using Anonymous Inner Class Block

Another alternative to initialize an object is to use the “Double Brace Initialization”. This will create an anonymous inner class with an instance initializer in it. Inside we can call the initialize method and pass values. In this way, we need not call the methods explicitly with reference.

Let us look at the implementation.

Different ways to create an object in java

We can create objects in different ways apart from using the standard way by using the new keyword. There are 4 ways to create objects:

  1. Using newInstance() method of Class
  2. Using newInstance() method of Constructor Class.
  3. Using clone() method
  4. By Deserialization.

Creating multiple objects by one type only

We can create multiple objects of one reference or class type. We did the same for variables with primitive data types while declaring variables of same type in one line.

Example:

Likewise, we can do the same for objects as well. We can create objects of Employee class same way. Instead of instantiating objects separately in two different lines we can write like this as well.

This feature makes objects in Java closely related to variables when it comes to the declaration syntax and being programmer friendly.

Anonymous objects in Java

Anonymous objects are the objects which have no references. In simple words, these are objects with no names and can be used at the time of object creation only. We cannot reference the members of the class like ordinary objects, i.e., anytime.

Anonymous objects are the best option when the objects have to be used only once.

Example: So, if we have to create an anonymous object of class Employee, it would look like:

To call methods using Anonymous Objects we do this:

Note: We cannot use Anonymous Objects to initialize member variables via methods. As no memory is allocated to such objects in the memory. However, we can instantiate the class using constructors with anonymous objects.

Now let us look at the program to use Anonymous objects and call methods from it.

Output:

Here, we see without constructor we get the already initialized values. However, with Constructors we get the values with which we instantiate the objects.

What is the difference between Class and Object in Java?

Now, let us have a look at the key differences between Class and Object in java.

 Class Object
1.  It is a blueprint or template for creating objects. 1. It is an instance of a class which has a state and behavior.
2. A Class characterizes a group of similar objects having same properties. 2. An object represents a real world entity with some attributes and features.
3. In java, Class is only loaded in memory during compile time for reference. 3. On the other hand, Objects are allocated memory dynamically as they are created during runtime .
4. A Class represents a logical entity which binds data and methods i.e. our code into a single unit. 4. An Object is a physical entity which provides us means to access the members of a class.
5. A Class is declared only once. We declare a class using keyword class. 5. Objects can be created more than once depending on the requirement. We declare objects using new Keyword.
6. We can define a class in only one way. 6. Whereas, we can create objects in multiple ways like: Using newInstance() method, Using clone() method etc.

So, that’s all about Object and class in java.

Related Posts

  • What is == in java
    01 December

    What is == in java

    Table of ContentsWhat is meaning of == in JavaCode example of ==Object equality using equal to ==The difference between == and equals== in EnumConclusion In this tutorial, we will learn what is == in Java as it is a common lexeme that we will use while developing applications. The == lexeme can be confused with […]

  • Multiple classes in one file in Java
    18 October

    Multiple classes in one file in Java

    Table of ContentsIntroductionMethods to Implement Multiple Classes In One Java Program1) Nested classes2) Multiple non-static nested classes In this post, we will see how to have multiple classes in one file in java. Introduction You need to have any number of classes in a single Java file, but there is a restriction that you can […]

  • Break out of nested loop in java
    22 July

    How to break out of nested loops in Java

    Table of ContentsUsing break (will break inner loop)Using named loopUsing named blockUsing returnConclusion In this post, we will see how to break out of nested loops in Java. Using break (will break inner loop) It is very important to understand how nested loops work to ensure that applying break will output the desired result. If […]

  • public static void main(String args[]) - Java main method
    11 June

    public static void main(String[] args) – Java main method

    Table of ContentsWhy is the main method so important?SyntaxExplanation of the KeywordsExamples of Java main method ProgramsSimple Java ProgramPassing arguments in the main methodNon-Public main method.Defining a return value for the main methodOverloading the main methodQuestionsCan we run java without main method?Can we have more than one main method in classConclusion If you have worked […]

  • Java projects for beginners
    30 April

    Top 20 Java Projects for Beginners

    This tutorial provides the top 20 java projects for beginners for practice. These projects will help you to learn java quickly and efficiently.

  • How to end program in java
    08 March

    How to end program in java

    Table of ContentsUsing System.exit() to end java programExample to demonstrate System.exit() methodHow to end java program in an if statement in javaUsing return to end current method Ho In this post, we will see how to end program in java. You can use System.exit(0) to end program in java. Using System.exit() to end java program […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.