简体   繁体   中英

How to make object in java. I have Test Class but not constructor

I'm very confused about object:

I'm creating a object Here is my Test Class : Test.java

public class Test {

     public static void main(String[] argc){
      Test obj; //1. ---> here object is created
      Test obj = new Test(); //2. --> or here object is created
      }
    }

Please

Every class without a self-coded constructor has the so called default contructor . This one is invisible and would have this code:

public Test() {

}

In line 1 you only declare a variable of type Test . In line 2 you actually create an object of type Test and assign it to the variable obj .

The first version

Test obj;

just declares obj value, not creates it. You can use it later in your code. Currently it contains null pointer, or points to nothing.

In the second version

Test obj = new Test();

combines declaration ( Test obj ), creation ( new Test() part) and assignment ( = ).

As explained in this java tutorial , Object creation as three parts:
1. Declaration : To declare obj variable:
Test obj;

It simply declares a variable. For primitive variables, this declaration also reserves the proper amount of memory, but for reference variables it does not create object.

  1. Instantiation : To instantiate obj variable:
    Test obj = new Test();


Operator new is required to allocate memroy for the obj and returning the reference to that memory. The new operator also invokes the object constructor.

  1. Initialization : To initialization obj variable it's constructor needs to be called. In Java, constructor is invoked by the new operator. In other languages eg C, C++ when you instantiate any variable using malloc it doesn't call constructor, which needs to be called explicitly. However new operator behaves similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM