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 :

1

2

3

4

5

class{

}

1

2

3

4

5

6

7

8

publicclass{

publicstaticvoidmain(String[]args){

}

}

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 keyword2 :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();

About the Author

Dear Friends,
I am A.K.M. .This online journal ai1tutorial.com is a humble effort from my side to all students and professionals who want to learn computer science related technologies.I am not a professional blogger and I write posts in this blog only in my leisure time.I may not be 100% perfect in all my posts,but your review comments can surely help me to make it 100% perfect.