Monday 28 April 2014

Constructor,Super(),this() in java



->The constructor is the first block of code. its called once the object created.

-> Constructor executes only once in the object lifecycle. its not execute after that.

-> it has the same name as the class name.

-> it can accept some arguments.

-> There is no return type for constructor. not even void.

-> if the class doesnot have the constructer, the default constructor will be generated by compiler with empty argument list. so only below code get execute.

car c new car();

-> if the class have any constructor, then its should match with constructor argument list and argument list while create object both should same, If it not match with any constructor argument then that statement will not get compiled.

car c new car(); //its not execute if class have any constructor.

car c new car(a,b); //Its execute if matched with constructor argument.




Super and this keyword

-> Super() is used to call parent class constructor.
this() is used to call same class constructor.

-> Super (with out paranthesis) is used to call parent class methods and variables.
this (with out paranthesis) is used to call same class methods and variables.

-> Both this and super not come together.

-> Super() and this() should be mentions in first line of constructor.



No comments:

Post a Comment