Java Object

In this chapter you will learn:

  1. Create objects from class
  2. Syntax to create objects
  3. Example - Create Java object
  4. Example - use a null mybox will result in a compile-time error

Description

When you create a class, you are creating a new data type. You can use this type to declare objects of that type.

Syntax

Creating objects of a class is a two-step process.

  • Declare a variable of the class type.
  • Use the new operator to dynamically allocates memory for an object.

The following line is used to declare an object of type Box:


Box mybox = new Box(); 

This statement combines the two steps. It can be rewritten like this to show each step more clearly:


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. After this line executes, mybox contains the value null. null indicates that mybox does not yet point to an actual object.

Any attempt to use mybox at this point will result in an error.

The next line allocates an actual object and assigns a reference to mybox. After the second line executes, you can use mybox as a Box object.

mybox holds the memory address of the actual Box object.

Example

A class defines a new type of data. In this case, the new type is called Box. To create a Box object, you will use a statement like the following:

 
class Box {/*w w  w . j a v a 2  s  . c om*/
  int width;
  int height;
  int depth;
}
public class Main {
  public static void main(String args[]) {
    Box myBox = new Box();
    myBox.width = 10;

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

The output:

myBox is an instance of Box. mybox contains its own copy of each instance variable, width, height, and depth, defined by the class. To access these variables, you will use the dot (.) operator.


mybox.width = 10;

This statement assigns the width from mybox object to 10. Here is a complete program that uses the Box class:

Example 2

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


class Box {/*  w ww.  ja  v a2 s .com*/
  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.

Next chapter...

What you will learn in the next chapter:

  1. Assigning Object Reference Variables
  2. Example - Java Object Reference Variable