Constructor is static or non static

后端 未结 11 1555
青春惊慌失措
青春惊慌失措 2021-02-04 12:33

As per standard book constructor is a special type of function which is used to initialize objects.As constructor is defined as a function and inside class function can have on

11条回答
  •  情歌与酒
    2021-02-04 13:10

    Static: Temp t= new Temp();

    The new operator creates memory in the heap area and passes it to the constructor as Temp(this) implicitly. It then initialise a non static instance variable defined in class called this to local parameter variable this.

    class Temp{
        int a;
        Temp this; //inserted by compiler.
        Temp(Temp this){ //passed by compiler
            this.this=this; // initialise this instance variable here. 
            this.a=10;//when we write only a=10; and all the non-static member access by this implicitly.
            return this; // so that we can't return any value from constructor.
        }
    }
    

    Constructor is static because:

    1. It is helping to create object.
    2. It is called without object.

提交回复
热议问题