Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

All About Object in Java

DZone's Guide to

All About Object in Java

Want to learn more about objects in Java? Check out this post to learn more about the different methods for creating an object in Java and how objects differ to classes.

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Introduction

In an object-oriented environment, it's a common requirement to create objects (instantiating a class), which is the basic building block for Java code. So, we have to know the object before creating and using them.

In a complex object-oriented environment, there will be lots of objects. Each object will have a role and responsibility — it's as simple as teamwork, for example, DAO, BO, and DTO. A DAO acronym, as a data access object, knows how to communicate with the back-end, which may not be known to the BO(business object). This is because BO will have a different role and responsibility.

This post will explain, in greater detail, the importance of creating an object and what happens internally when we are creating an object. 

How an Object Is Different From a Class?

There seems to be a lot of developers having doubts and thinking that objects and classes are the same.

Conceptually, both are different. A class is a blueprint to create an object. There is no existence of a class without an object — in other words, an object is representing a class.

For instance, let's consider Animal. In particular, there is nothing called "animal;" it's just a common terminology that indicates to a group, category, or class. If I tell dog or cat, then, it's existing, and you can use dog or cat as a prototype of an Animal . In this case, dog is an object that represents the Animalclass. So, under a class, we can create objects, whereas, vice-versa is not applicable conceptually.

I hope you now have a clear picture about objects and classes!

Are Object and Instance the Same in Java?

Here, we will discuss how objects and instances are related, as far as Java is concerned. Technically, an instance is a variable that holds an object. In other words, instance is a handler for an object.

ABC instance1 = new ABC();


Here, ABC >>   is a class, and  [new ABC();] >> , as a whole, is an object. Instance1 >> is an instance or variable of the type (user defined datatype) ABC.

In the above case, the new  ABC() is enough to create an object. Technically, we don't need an ABC instance1 , but, for further use, we have to store/assign the state of an object to a particular instance/variable, because, in Java, each and every object is unique. Later on, we will discuss this in greater detail (hashcode, hashvalue, etc).

In common practice, you can consider an instance as an alias for an object. Both are the same, as per Java is concerned; however, it is a different story for C and CPP.

Take Advantage of the instanceof Operator

 instanceof  is a keyword that you can use to check whether an instance belongs to a particle object or not.

Why and When to Create an Object?

Basically, in programming, we are using a lot of veritables and blocks. Each veritable and block needs some amount of memory. Memory is a resource of an operating system. As a Java programmer, we don't have direct access to memory — it's highly encapsulated.

JVM is allocated to a few amounts of RAM, based on OS specification, which is well known as runtime area. All static and non-static members will use this based on the demand and requirement.

As per each class member is concerned, we can divide the memory allocation into two parts. First, one is static members, which will allocation memory, while using the class loading by the class-loader   itself (an operation done by JVM to make the programme into process, if you want, you can implement your custom class loader).

Second, we will look at allocating memory to a non-static member, where we have to create objects for allocating memory. In other words, we will allocate memory on demand dynamically. So, the benefit is that there is no need to load all the members statically,  like "C programming," because we may not use all members at time, so it's unnecessarily wasting memory that can be used by some other resource.

Object Internals and How Objects Work

From our previous discussion, we came to the conclusion that, to assign memory dynamically, we need to create an object. But, now, the question arises about how the internal process is carried out and what actually happens.

This is a brilliant question; and, we have the answer for you. To understand the answer, you have to know your constructor better (we are assuming you have basic knowledge about inheritance).

Role of the Constructor on Object Creation

Do not forget, as far as Java is concerned, the super class of all classes is the object class. If a class doesn't extend to any class, then, by default, it extends the object class.

For example, I can write >> class A{...}  equivalent to Class A{...}   extends Object{...} . 

Before proceeding any further, to solve the following debugging problem with the "role of constructor on object creation," check out the following code:

If you could observe the above programm, then, you must have gotten the following output:

ObjectAndConst objectandConst = new ObjectAndConst();


Yes, whenever you are creating an object, you are calling the constructor. In the above snippet,  ObjectAndConst()  means that we are calling a constructor. If a constructor is already there, then JVM will pick that one. Otherwise, the default constructor will come into action.

While creating an object for a class, first, it will call to that particular class constructor, and, as you know that the first line of each constructor is a keyword, it will call to the super class constructor.

In our case, ObjectAndConst   class's super class is ObjectAndConstBase ,  and, again, ObjectAndConstBase   will call to the Object  class constructor (the super class of all classes is the object class, if that class doesn't extend to any other class). After completely executing the object class constructor, the control will come to calling a place, i.e. the ObjectAndConstBase  class, and it will execute the rest of the code. The control will call back to the ObjectAndConst  as the execution started from that place.

In this whole process, we are not only creating an object of the ObjectAndConstclass, but we are are creating three objects. The first one is for the object class, which will create the first and second one in the ObjectAndConstBase , and, finally, ObjectAndConst means that we create three different objects (chain of the object) and assign it to the instance of the ObjectAndConst class:


Different Ways to Create an Object

There are several different ways to create an object. Here, we will discuss five different ways to create an object.

1. Using New Keywords

This is the most common way to create an object in Java. I read somewhere that almost 99 percent of objects are created in this way.

ABC object = new ABC();


2. Using Class.forName()  

If you know the name of the class and it has a public default constructor, we can create an object like this:

ABC object = (ABC) Class.forName("org.JavaInCloud.java.ABC").newInstance();


3. Using clone()  

The clone() can be used to create a copy of an existing object.

ABC anotherObject = new ABC(); 
ABC object = anotherObject.clone();


4. Using the Object Deserialization

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
ABC object = (ABC) inStream.readObject();


5. Using the Factory Method

Basically, we are using this object creation method in the singleton designing pattern where we can't directly create one object using a new operator. One static method will be there which will create an object and return the class instance, which is known as the factory method.

Conclusion

I hope you enjoyed this post on creating objects in Java. Feel free to comment in case of any questions or suggestions.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:
object ,ooad ,java ,oop concept

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}