World's most popular travel blog for travel bloggers.

Declaring object in class in java

, , No Comments

Declaring Object in Class : Declaring Reference to an Object in Java Programming

  1. When we create class then we are creating new data type.
  2. Newly created data type is used to create an Object of that Class Type.
  3. Creating object is two step process.

Creation of Object involves two steps –

  1. Declaration
  2. Allocation and Assigning
Rectangle myrect1 = new Rectangle();
this statement is used to create an object we are going to break down this statement in two separate statements –
Rectangle myrect1 ;
myrect1 = new Rectangle();


Step 1 : Declaration of Variable of Type Class



  1. Above Declaration will just declare a variable of class type.
  2. Declared Variable is able to store the reference to an object of Rectangle Type.
  3. As we have not created any object of class Rectangle and we haven’t assigned any reference to myrect1 , it will be initialized with null.

Step 2 : Allocation and Assigning Object to variable of class Type


  1. Above Statement will create physical copy of an object.
  2. This Physical Copy is then assigned to an variable of Type Class i.e myrect1.
  3. Note : myrect1 holds an instance of an object not actual object. Actual Object is created elsewhere and instance is assigned to myrect1.

In short –

  1. First statement will just create variable myrect1 which will store address of actual object.
  2. First Statement will not allocate any physical memory for an object thus any attempt accessing variable at this stage will cause compile time error.
  3. Second Statement will create actual object ranndomly at any memory address where it found sufficient memory.
  4. Actual memory address of Object is stored inside myrect1.

0 comments:

Post a Comment

Let us know your responses and feedback