Saturday, November 26, 2016

Super Keyword - Keyword pass an argument

      

                                                  This Keyword used to refer the current object

In java this keyword is used to refer the current object. Through the use of This keyword we can access the current class instance variable, we can invoke current class constructor, we can also have passed this keyword as an argument.
 Keyword pass  an argument


Example as a current class instance variable


instance variable

Now in above example

 we create two constructorsin which one constructor contain one argument and second constructor contain two arguments the instance variable name and constructor parameter name both are same. When I call first constructor then inside of that constructor it is
age = age;
Now this creates some confusion the compiler should take parameter variable and assign it with again parameter variable so, as we know scope of parameter variable which is within method not outside of the method so that’s why it displays default integer value which is zero. Keyword pass  an argument

Now in second constructor we pass two arguments with same name as instance variable. now inside that constructor it is  (Keyword pass  an argument)
this.age = age;
this.name = name;
Now this.age and this.name refers the current class instance variables, age and name are parameterized variables. So, whatever value we will pass when we call the constructor than that value will be assign to the instance variable by the use of this keyword.
 Keyword pass  an argument

Example to invoke current class constructor.

invokeCurrent clsConstructor

Now in above example I create four constructors, first constructor is without parameter, second constructor with one parameter, third constructor with two parameters and forth constructor with three parameters. Now to access constructor inside the constructor we have to use this keyword

Like in second constructor I use this keyword like this: “this()” it call that constructor which having no any parameter. Same way in third constructor I used this keyword like: “this(rollNo)”, it calls that constructor which having on integer argument. this() is always the first statement of the constructor otherwise you will get compile time error.


 Keyword pass  an argument

        Super Keyword

In java super keyword is used to invoke parent class constructor, variables and methods. Whenever we create constructor for subclass, then reference of super class automatically created with super().
 Keyword pass  an argument

Example with Variable

SuperVariable

Example with Constructor and Method

SuperMethod

 Keyword pass  an argument








No comments:

Post a Comment