When does the Constructor get called?
Before object creation.
During object creation.
After object creation.
The object memory is allocated, the field variables with initial values are initialized, and then the constructor is called, but its code is executed after the constructor code of the object super class.
At the byte code level.
An object is created but not initialised.
The constructor is called, passing the object as this
The object is fully constructed/created when the constructor returns.
Note: The constructor at the byte code level includes the initial values for variables and the code in the Java constructor.
e.g.
int a = -1;
int b;
Constructor() {
super();
b = 2;
}
is the same as
int a;
int b;
Constructor() {
super();
a = -1;
b = 2;
}
Also note: the super() is always called before any part of the class is initialised.
On some JVMs you can create an object without initialising it with Unsafe.allocateInstance(). If you create the object this way, you can't call a constructor (without using JNI) but you can use reflections to initialise each field.
It gets called at object creation. The memory must be reserved first for the object, otherwise the constructor code could not run. So maybe we could say after object creation. Also note that initialization code written in the class gets called before the constructor code.
public Ex {
int xVal = -1;
int yVal;
public Ex() {
// xVal is already -1.
//yVal defaults to 0.
}
}
THE JVM will first allocate the memory for your object, then initialize all fields, then invoke your constructor.
The constructor gets called when a new object is created.
NewObject n = new NewObject();
public class NewObject {
public NewObject() {
// do stuff when object created
}
}
Hope this helps.
basically constructors are called to initialize the values of the instance variables except the case for default constructors. However, this initialization of the instance variables are done in 4 steps (as applicable):
variables are initialized with default values (ints with 0, chars with u\0000 etc.)
variables are initialized with explicit initialization values
initialized with static blocks
constructors are called
After the Object creation
once an object is created using new operator like Student s = new Student();
first Student object is created, and then constructor is called to initialize the variable of the object
We can prove constructor is called after creating the object by using below code
here we are using instance block. And also instance block is executed before the constructor
so I am printing hash code in three places
Inside Instance block
Inside Constructor
Inside main mehtod
all these three times hash code is equal, that means object is created before the constructor is executed
because having a hash code means, there must be an object. And if hash code printed inside both instance block and constructor is equal. that means object must be created before the constructor execution
Constructor is what practically creates object. It is called when object is created by executing new MyClass() (or its parametrized version).
Given those options, 1. Before object creation.
After the constructor finishes, the object has been created.
Whenever we create an object by using 'new' operator then 1st task is performed by the new i.e. it allocates the memory for object in heap with pointing to the reference variable in stack and set the initial values of object fields.then it calls the constructor with passing 'this' as object to initialize it according to your requirement...
So the constructor is always called after the object creation....
Note: When you enter in constructor so 'this' keyword is working means your object has been created.
Related
I am confused as to the purpose of empty constructors, let me ellaborate:
if I have a class..
public class Test {
private int x;
private int a[];
private static int y;
public Test() {
a = new int[3];
}
}
I know that there exists an empty default constructor:
public Test() {
//or at least I think it exists
} //what is its purpose?
if I have a main method and code the following:
Test t1 = new Test();
Which constructor is called? or is the empty constructor overwritten by the one which instantiates a[]?
If I then instantiate 5 instances of Test, how many integer memory locations are allocated?
Sooo confused....
The empty constructor is inherited from the Object class, which is the superclass of all classes in Java. It merely allocates memory of the objects, but does not initialize anything.
So for every object it is possible to call new A(), even if public A() is not defined explicitly.
Sometimes you don't need to do extra job in the constructor, so you can just use the default one without bothering reimplementing it.
When a child class overwrites it, then the one called is the new one. It makes perfect sense, because when you bother overwriting a method, you want to be able to use it instead of the default one.
In your examples, the Test class contains 2 integers, and an array of 3 integers.
Each time you instantiate a new Test, you allocate space for two more integers and the array of three integers. This is why those are called instance variables: it means they belong to an instance. So each instance has its own.
If you do not define any constructor for your class then compiler will automatically add a default parameter-less constructor to your class definition so that objects can be created using new keyword. If you explicitly define a parameter-less constructor (the way you have done) yourself then compiler will not add anything from his side.
So in this line of code
Test t1 = new Test();
the constructor that you have defined explicitly will be called.
To answer your second question - Each instantiation of your class results in allocation of memory required to hold an array containing 3 integers. For 5 instances it will simply become 5 times.
i.e. 5 * 3 * memory occupied by one integer
Which constructor is called? or is the empty constructor overwritten by the one which instantiates a[]?
Since you have provided constructor for Test class, your constructor will be called. If you want to call super class constructor explicitly, change your code as
public Test() {
super();
a = new int[3];
}
From oracle documentation page on constructors
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor
If I then instantiate 5 instances of Test, how many integer memory locations are allocated?
JVM will allocate space for 1 integer for static variable ( int y, which is class or static variable)
JVM will allocate space for 1 integer for each Test instance for int x, which is instance variable
JVM will allocate space for 3 integers for each Test instance for int a[] array, which is instance variable
Total : Space for 5 + 5 + 15 (=25) integers
I just want to make clear that to call a function in two forms like
By creating an object and calling the method by using that object.
Without creating a object calling the function.
I mean for instance i have a class like
Class A{
public int callMethod(){
return 2;
}
}
Now I am creating another class to call the method callMethod defined in the Class A
Class B {
public static void main(String[] args) throws ParseException {
A a = new A();
//1st form to call the method
int aa = a.callMethod()
System.out.println(aa);
//2nd form to call the method
aa = new A().callMethod();
System.out.println(aa);
}
}
here in the first statement after creation of a object i am calling the callMethod() of class A by using the class object of A. And in the second time i am calling the method directly without creating the object class A. In the first form calling the method it is damn sure that we are creating the object and occupies some space in the memory for the object. Then what about the second form calling the method? Will it take any object creation? Which one is quicker? can anyone give me the clarifications on this.
When you use new keyword and constructor, in this case, new A(), it is creating a new object.
And in the second time i am calling the method directly without
creating the object class A.
That's not true - the object is still created, it only has no name you can refer to afterwards.
Both of your ways are creating an instance of the object but in second case you don't have variable to point to the object if you want to access the second object later you can not do it
In the second code you are creating an instance of A and it is occupying space on the stack.
The first code will require that you instantiate A on the heap space (Unless you instantiate it from static code, for example:
static {
A a = new A();
}
)
You are creating objects in the BOTH the methods. The statement
new A()
creates a new object and then you are calling a function.
You should also know that objects DO NOT get different memory space for methods. All the objects of a class share the same memory space for methods. so it really doesnt matter about the space.
If you want to call a function without using a object, you should make the function static, that way you cam call the function without actually using an object.
hope this helps.
Read about stack space and heap space in java
In java we have references referring to objects on heap space,
In both cases, it is creating object on heap space but in first case
you have reference stored on stack space with A a ("a" is reference)
So in same method or any other methos to which this reference is
passed can refer to the original object (first object created) from
heap space...
In second case you are calling methos directly on new obj which has no
reference stored on stack space to refer it afterwards like in first
case.
Both are same..!!
When you write
new A();
here Compiler calls the Non-parameterized constructor (if it is not written by programmer compiler calls the default constructor )
like:
A()
{
//i am default constructor
super();
}
note: here super(); call the immediate super-class default constructor which is the Object class and object is created.
A a = new A();
here object is created and you assign that object to reference 'a';
Why we instantiate some object inside constructor and some outside. What are the advantage/ disadvantages of doing this.
public class HomePage_Util {
private Common_Functions cfObj = new Common_Functions();
HomePage_OR home_ORobj;
Logging logObj = new Logger();
public static String scptName;
public ArrayList<String> homeScriptMsgList = new ArrayList<String>();
public HomePage_Util(WebDriver driver) {
home_ORobj = new HomePage_OR();
PageFactory.initElements(driver, home_ORobj);
}
Objects are initialized in constructors only when they are needed to initialize other objects in a sequence. Like in your example first of all the object i.e. home_ORobj = new HomePage_OR(); will be created as this object is needed to initialize the PageFactory elements in next step.
So if home_ORobj = new HomePage_OR(); is not needed to initialize the PageFactory elements then you could write it out of the constructor i.e. globally.
Code reuse is the main advantage of initializing elements in a constructor. Also initializing few things makes sense only when the object is created or constructor is called.
Constructor is basically for creating a new object of a class. When you create an object, a copy of all variable for that object is created and assigned default value.
The purpose of initiating some variables in constructor is to assigned the value at the time of creation of an object. So that you don't have to assigned value implicitly.
My guess is the writer of such code wasn't sure if home_ORobj would be initialized before the call to initElements() but the ones outside are initialized first so it doesn't matter.
Though if they depend on each other (i.e. use another in the parameters to the constructor) it's good to put them in the constructor as code formatters may re-order the list of elements breaking the the code.
Some objects requires few fields to be initialised in order to correctly construct that object before it being used. Constructor is called when the object is getting created, hence it is initialised in constructor.
You can have overloaded constructor with different initialistion for different scenarios.
You can always have a method called initializeValues and call it after you create an object rather than putting it in constructor.
Putting it in constructors will ensure that it is always called when you create an object.
Super class constructor is always called before the derived class constructor, so it makes sense.
One advantage is to avoid a static block to initialize static members.
AFAIK It's not exactly the same in the lifecycle of an object : constructor is executed after the firsts initializations.
An instance field that is initiated outside a constructor is always going to be that way initially when a new object is created - for every instance. The ones initiated in a constructor may have some special meaning for the new instance such as the WebDriver in your example seems to have so it cannot be initiated elsewhere. A constructor that requires an instance of certain type to be passed as an argument does enforce design since it cannot be passed anything else and cannot be constructed without it.
A class may contain multiple constructors that may behave differently and instantiate different fields and leave others untouched (like when there are multiple purposes for a class, which actually may indicate bad design).
Additionally, if a class does not have a default constructor => upon deserialization no constructor's get called.
class A
{
B b;
public A()
{
b = new B(this);
//initialization of class A variables
}
public void meth1()
{
}
}
class B
{
A a;
public B(A a)
{
this.a = a;
}
}
I know that this reference shouldn't be passed in this way,but what happens if this is done
Some other class calls the class A constructor. when is the "this" reference actually allocated memory? would it be assigned memory as soon as A's constructor is called before even super() is called.
Suppose class B is a thread and since B has A's reference can B call the methods on A before A's constructor doesn't even return if "this" reference is not allocated memory yet.
The memory for the object is allocated before any constructor is executed. Otherwise the constructor would have not place to write the values of the variables.
Therefore you can pass out a reference to the current object (a.k.a this) to other pieces of code inside the constructor.
As you noted, the object is not fully constructed at that time and it's a bad idea to actually do that, but "just" because the values of the object can be in an inconsistent state. The memory is already allocated and reserved for that object at this point in time.
this is just a reference to the "current object", which you could think of as just another parameter that any non-static method gets. In fact in that's actually how the JVM treats it. See JVMS ยง2.6.1 Local Variables:
On instance method invocation, local variable 0 is always used to pass a reference to the object on which the instance method is being invoked (this in the Java programming language).
So the direct answer to "when is this allocated" is effectively: Whenever you call a method on an object.
this refers to current object and any object is allocated memory using "new"
The memory is allocated when JVM is processing new instruction. If for example your code looks like:
A a = new A();
^
here the memory for A is allocated
It indeed could be a problem to pass this to B. Constructor of B can invoke instance method of A before the constructor of A has been finished. You should move line to the end of constructor of A to avoid possible problems. Alternatively you could manage the object lifecycle from outside using setters.
this is assigned before the constructor is called. In fact, the super() call is not necessary. It only ensures that the creation stuff of the parent class is done, which doesn't matter if the parent class is Object. Also, A's methods are usable as soon as the object is created (even before the constructor is called) so if B got the reference to A in the constructor, it can use A's methods just like A itself in the constructor. Just be sure to make A's methods so that they can be used when A is not fully initialized, or just create and start B after the initialization is complete.
As long as you don't modify A or call methods on A or it's members in the constructor of B it will work. ( See other answers)
If you call a method on an not completely initialized object (after construction) it's not defined what happens. Especially if you use multiple threads (see memory barrier).
More on this topic:
How do JVM's implicit memory barriers behave when chaining constructors?
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?
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.
Constructors are non-static. Every method first parameter is implicit this (except static) and constructor is one of that.
Constructors are NOT static functions. When you do Test test =new Test(); a new Test object is created and then the constructor is called on that object (I mean this points to the newly created object).
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.
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
Not static. Read about constructors http://www.javaworld.com/jw-10-2000/jw-1013-constructors.html.
Neither.
Methods can be divided into 2 types: static/non-static methods, aka class/instance methods.
But constructors are not methods.
When we talk about static class then it comes to our mind that methods are called with class name,But in case of constructor ,Constructor is initialized when object is created So this proves to be non-static.
Constructors are neither static (as called using class name) or non-static as executed while creating an 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 initializes a non-static instance variable defined in a class called this to the local parameter variable this.
Below example is just for understanding the concept, if someone tries to compile it, it will give the compile-time error.
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:
It is helping to create object.
It is called without object.
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