Constructor is static or non static

后端 未结 11 1587
青春惊慌失措
青春惊慌失措 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:04

    Your second example hits the spot. this reference is available in the constructor, which means constructor is executed against some object - the one that is currently being created.

    In principle when you create a new object (by using new operator), JVM will allocate some memory for it and then call a constructor on that newly created object. Also JVM makes sure that no other method is called before the constructor (that's what makes it special).

    Actually, on machine level, constructor is a function with one special, implicit this parameter. This special parameter (passed by the runtime) makes the difference between object and static methods. In other words:

    foo.bar(42);
    

    is translated to:

    bar(foo, 42);
    

    where first parameter is named this. On the other hand static methods are called as-is:

    Foo.bar(42);
    

    translates to:

    bar(42);
    

    Foo here is just a namespace existing barely in the source code.

提交回复
热议问题