Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor is static or non static

Tags:

java

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 only two type either static or non static.My doubt is what constructor is ?

1.)As constructor is called without object so it must be static

  Test test =new  Test();//Test() is being called without object
   so must be static

My doubt is if constructor is static method then how can we frequently used this inside constructor

Test(){
    System.out.println(this);
}

Does the output Test@12aw212 mean constructors are non-static?

like image 894
Arun Avatar asked Oct 17 '12 17:10

Arun


People also ask

Can constructor have static?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

What is non-static constructor?

Static constructors are used to initialize the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initialize the non-static members of the class.

Is constructor by default static?

Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables. On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.

Can a constructor be final or static?

No, a constructor can't be made final. A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.


1 Answers

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.

like image 70
Tomasz Nurkiewicz Avatar answered Nov 06 '22 08:11

Tomasz Nurkiewicz