Home » Core Java » class and Object in Java

class and Object in Java

The primary goal of Java is to keep things simple.This is the main reason why Java programs are very easy to write and understand unlike other programming languages.In this chapter we will learn about class and object.

what is a class ?

To start a java program we need to write a class first.Without class, there is no java programming.

A class is an entity that holds state and behavior. State is represented by variables and behavior is represented by methods that operate on the state.A java project  can be a single class or a collection of classes.Out of all the classes  main class is the only top level class from where the program actually begins and ends.

Syntax :

 
 
What is an Object ?

Object is an instance of a class. Class is a template or blueprint from which objects are created.If you see a bike model or template ,you can consider it as a class ,while the actual physical bike is the object.So,class is a logical entity and object is a physical entity.

An object is an entity that holds state,behavior and identity or existence.State is represented by variables and behavior is represented by methods that operate on the state and identity or existence means presence in java heap memory with unique id.

Ways to create object :

There are 4 different ways to create objects in java:

1 : By using new keyword
2 : By using Class.forName()
3 : By using clone()
4 : By using Object Deserialization

Suppose the class name is Example for which we are going to create object.

By using new keyword :
By using new keyword and following the below syntax we create object of the class and the object gets memory allocated in Java heap area.
Example object=new Example();

By using clone():
The clone() method of Object class can be used to create a copy of an existing object.
Example obj=new Example ();
Example object=(Example )obj.clone();

By using Class.forName() :
With the help of reflection API,If we know the name of the class which has a public default constructor we can create an object.
Class clazz=Class.forName(“Example”);
Example object=(Example)clazz.newInstance();

By using Object Deserialization :
By using Object deserialization ,we can create object from its serialized form.
ObjectInputStream istream=new ObjectInputStream(some data);
Example object=(Example) instream.readObject();


Leave a comment

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

15 + 20 =