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
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.
Constructor is used to initialize the object and has the behavior of non-static methods,as non-static methods belong to objects so as constructor also and its invoked by the JVM to initialize the objects with the reference of object,created by new operator
The new
keyword here is the trick. You're correct in noting that in general, if you're calling it without an object, a method is static. However in this special case (i.e., preceded by the new
keyword) the compiler knows to call the constructor.
Neither.
Methods can be divided into 2 types: static/non-static methods, aka class/instance methods.
But constructors are not methods.
The new
operator returns a reference to the object it created.
new Test(); // creates an instance.
The System.out.println(this);
is called after the new
operator has instantiated the object
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: