OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 2 : Declaring Objects

Unit - 2

Topic 2 : Declaring and Creating Objects in Java

Declaring objects of a class is a two-step process in Java:

Step 1: Declare a reference variable

Before we can use an object, we must declare a reference variable of the class type.
This variable doesn’t create the object — it just stores the reference (memory address) of an object once it is created.

Example:

Box mybox; // declares a reference variable of type Box

Here, mybox is null by default (it doesn’t refer to any object yet).


Step 2: Create the object using new

To actually create the object in memory, we use the new operator. The new operator:

  1. Allocates memory for the object.

  2. Returns a reference to the object (similar to a memory address).

Example:

mybox = new Box(); // creates a Box object and assigns its reference to mybox

Combining both steps

In most cases, we combine the declaration and creation in one line:

Box mybox = new Box();

This means:

  1. Declare mybox as a reference to a Box object.

  2. Create a Box object in memory and assign its reference to mybox.





Example Program: Declaring and Creating Objects

class Box { double width; double height; double depth; void volume() { double vol = width * height * depth; System.out.println("Volume is " + vol); } } public class ObjectDemo { public static void main(String[] args) { // Step-by-step declaration and object creation Box box1; // declare reference variable box1 = new Box(); // create object // Combined declaration and creation Box box2 = new Box(); // Assign values to box1 box1.width = 10; box1.height = 20; box1.depth = 15; // Assign values to box2 box2.width = 5; box2.height = 6; box2.depth = 7; // Display volumes box1.volume(); box2.volume(); } }

Sample Output

Volume is 3000.0 Volume is 210.0

Key Points to Remember

  • A class variable is just a reference; the actual object is created using new.

  • If you declare a reference but don’t assign an object, it will be null. Accessing it will cause a NullPointerException.

  • You can create multiple objects from the same class, each with its own data.

Example:

Box b1 = new Box(); Box b2 = new Box(); 

Here, b1 and b2 are two separate objects in memory. 

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies