Declaring Objects

In this chapter you will learn:

  1. How to use class as a type and create new variables
  2. What are Object instance
  3. How to new operator to create new object instance
  4. How to assign object reference variables

Use class as a type

Object creation is a two-step process.

  1. declare a variable of the class type.
  2. acquire a physical copy of the object and assign it to that variable using the new operator.

The new operator dynamically allocates memory for an object and returns a reference to it. The following lines are used to declare an object of type Box:

Box mybox; // declare reference to object 
mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. mybox is null now. The next line allocates an actual object and assigns a reference to it to mybox. It can be rewritten to:

Box mybox = new Box();

Any attempt to use a null mybox will result in a compile-time error.

class Box {//j  a  v  a2 s . c o m
  int width;
  int height;
  int depth;
}

public class Main {
  public static void main(String args[]) {
    Box myBox;
    myBox.width = 10;
  }
}

If you try to compile the code above, you will get the following error message from the Java compiler.

Object instance

The following program declares two Box objects:

class Box {//  j a v  a2 s  . c  o m
  int width;
  int height;
  int depth;
}

public class Main {
  public static void main(String args[]) {
    Box myBox1 = new Box();
    Box myBox2 = new Box();

    myBox1.width = 10;

    myBox2.width = 20;

    System.out.println("myBox1.width:" + myBox1.width);
    System.out.println("myBox2.width:" + myBox2.width);
  }
}

The output produced by this program is shown here:

new operator

The new operator has this general form:

classVariable = new classname( );

The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created.

Assigning Object Reference Variables

Consider the following code:

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

b1 and b2 will refer to the same object. Any changes made to the object through b2 will affect the object b1. If b1 is been set to null, b2 will still point to the original object.

Box b1 = new Box(); 
Box b2 = b1; 
// ... 
b1 = null;

Assigning one object reference variable to another only creates a copy of the reference.

Next chapter...

What you will learn in the next chapter:

  1. What are the three types of class variables
  2. How Java class member variables got initialized
  3. How does automatic variable(method local variables) got initialized
  4. How does Class variable (static variable) got initialized