Creating Objects

As we have seen earlier a class provides the blueprint for objects. A class creates a logical framework that defines the relationship between its members. An object in Java is essentially a block of memory that contains space to store all the instance variables.

It can also be considered as a variable.

Obtaining objects of a class is a two-step process

  1.  Declaring variable of the class type
  2. Acquiring an actual, physical copy of the object and assign it to that variable.

Box mybox = new Box();
The above line creates an object of the Box class. Here it combines two statements into a single statement. It can be rewritten as -
Box mybox; //declare reference to object
mybox = new Box(); //allocate a box object

Here, first line declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null. Any attempt to use mybox at this point may cause a compile-time error.

Second line allocates an actual object and assigns a reference to it to mybox. mybox simply holds the memory address of the actual Box object.

Declaring an object of type Box

New keyword

The new operator dynamically allocates memory for an object. It has the general form of 
class-var = new classname();
here class-var is a variable of the type class.
The classname is the name of the class that is being created. The class name followed by parenthesis specifies the constructor for the class.
A  constructor defines what occurs when an object if a class is created.

The new keyword allocates memory for an object during run time.

Here one question may come into mind that why there is no need to use new for integers or characters. The answer is that java's primitive types are not implemented as objects. They are implemented as normal variables.

Assigning Object Reference Variables

take a look at the code below -
Box b1 = new Box();
Box b2 = b1;

In the C programming language whenever we were assigning any variable to another variable it was creating a copy of that data and assigning it to another variable.

But, in Java whenever we assign any object variable to any other variable both variables will refer to same object. In above example b1 and b2 both refers to the same object.


Although b1 and b2 both refers to the same object they are not linked in any other way.

When you assign one object reference variable to another object reference variable, you are not creating a copy of the object you are only making a copy of the reference.


Comments

YouTube

Popular posts from this blog

GTU OOP Programs - 11

Mini project ideas for Operating System

GTU OS Program - 9