Wednesday, July 22, 2020

"this" keyword in java

"this" keyword


If instance variable and local variable name is same i.e. a=a in example, it'll print the value of instance value:



package code;

public  class ThisKeywordTest {
 int a;


 void setValue(int a) {
a=a;

}
 void show() {
System.out.println(a);
}


public static void main(String[] args) {

ThisKeywordTest ob = new ThisKeywordTest();
ob.setValue(4);  
ob.show();
}

}
o/p: 0
---------------------------------------------------------------------------------------------

To resolve the issue we'll use this keyword.

package code;

public  class ThisKeywordTest {
 int a;


 void setValue(int a) {
 this.a=a;

}
 void show() {
System.out.println(a);
}


public static void main(String[] args) {

ThisKeywordTest ob = new ThisKeywordTest();
ob.setValue(4);
ob.show();
}


}
o:p= 4




Add caption





CONSTRUCTOR in java

Why we need constructor in java?

Before constructor, we initialize the variables and object by creating objects. e.g.
ob.emp_id=101;
ob.emp_name="Manoj";
.
.
.

If there are 1000 employes in the company we need to created 1000 objects and 2000 lines to intialize the values of object.{which is not good programming}
but after using constructor, we can intialize the values of instance variable by using parameterizes constructor.

Employee ob = new Employee(102,"Parisha");

There are 3 types of constructor:
1.)Default constructor,
2.)User defined constructor: no-argument constructor, parameterized constructor.
NOTE:
1.) constructor is created by COMPILER, Not by JVM.
2.) If user defined constructor is created then , Default constructor will not be Created. compiler tabhi default constructor create krega jb hum khud se koi constructor create nhi krengey.

constructor ka return type kyo nahihota?
answer:
1.) constructor ka kam object ko initialize krna hota hai, jb onject k ander values initialize krni hai to return type to wo kuch krega hi nahi.

2.) Compiler ye predict nahi kr skta k constructor ka return type kya hoga.








Guitar Chords

click on   Guitar Chords Family