Class, Object & Anonymous object in Java

·

2 min read

What is Class?

Class is Blue print on an Object, It is not possible to create an object without class.

Or

Class is logical entity which plays vital role in creating objects.

Syntax for creating class in Java

class classname

{

//Attributes of class

}

What is Object?

Objects: Objects are real world physical entity

Each Object will have state and behaviour

State: All the data members associated with class are termed as state

Behaviour : All the Member function are considered as behaviour

In Java it is possible to create object in 5 ways

  1. New keyword

  2. Clone method

  3. Class.forNane()

  4. Object input stream (Deseriaisation)

  5. Reflection API

In this blog I will explain steps to create object using new keyword.

Steps to create object:

  1. Define public concrete class

  2. Define all the attribute and behaviour

  3. Follow the syntax to create object

    class name obj references = new className();

Example

class Employee

{

public String name;

void info()

{

System.out.print(“hello ”+name+ “welcome to my blog”);

}

public static void main(String[] tags)

{

Employee emp = new Employee();

emp.name =“tom”;

emp.info();

}

}

Flow of execution of the code :

JVM search for main method and start executing it, in main method employee object is created with new keyword hence employee object will get stored in heap area and JVM will allot some address to it. JVM also assign name variable as tom. Post initialisation info() is called info() is get executed printing “Hello tom welcome to my blog”.

Anonymous object

The object without the object reference or object name are termed as anonymous object.

Example demonstrates anonymous object for class Employee:

new Employee() // anonymous object