How to Create objects from class?

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 {

  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);

  }

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

 

class Box {

  int width;

  int height;

  int depth;

}

 

public class Main {

  public static void main(String args[]) {

    Box myBox;

    myBox.width = 10;

  }

}