Object creation in Java

Creating a Java object

In Java, you can declare an object as follows, and if you declare an object, you can create an actual object like the second sentence.

ClassName ObjectReferenceVariable;
ObjectReferenceVariable = new ClassName ();

To create an object like this, you first need to declare and create an object. The above two statements can be written in one sentence as shown below.

ClassName ObjectReferenceVariable = new ClassName ();

In the actual code, it is generated as follows.

class Box {
  int width;
  int height;
  int depth;

class MyBox {
  Box myBox1;
  Box myBox2;
  myBox1 = new Box();
  myBox2 = new Box();

Declaring an object initially implies a variable with a null value. When you create an object, memory is allocated for the object, and the object reference variable has a reference to the object.

class Box {
  int width;
  int height;
  int depth;

class TwoBox {
  public static void main(String args[]) {
    Box myBox1 = new Box();
    Box myBox2 = new Box();
    int vol1, vol2;

    //Create first box object
    myBox1.width = 20;
    myBox1.height = 40;
    myBox1.depth = 15;

    //Create second box object
    myBox2.width = 10;
    myBox2.height = 20;
    myBox2.depth = 30;

    vol1 = myBox1.width * myBox1.height * myBox1.depth;
    System.out.println("The size of the first box is " + vol1);

    vol2 = myBox2.width * myBox2.height * myBox2.depth;
    System.out.println("The size of the second box is " + vol1);
Basic example of object creation

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post