Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to produce current class way(method) (implicitly)
3. this() can be used to produce current class creater.
4. this can be passed as an argument in the way(method) call.
5. this can be passed as argument in the creater call.
6. this can be used to return the current class instance from the way(method) .
class Coding{
int rollno;
String name;
float fee;
Coding(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+” “+name+” “+fee);}
}
class TestThis2{
public static void main(String args[]){
Coding s1=new
Coding(111,”vishnu”,5000f);Coding s2=new
Coding(112,”ram”,6000f);s1.display();
s2.display();
}}
Output:
111 vishnu 5000
112 ram 6000
Difference between creater and way(method) in java
Â
Java Creater                                                             Java Way(method) |
|
Creater is used to institute the state of an object. | Way(method) Â is used to expose behaviour of an object. |
Creater must not have return type. | Way(method) Â must have return type. |
Creater is produce implicitly. | Way(method) Â is produce definitively. |
The java compiler gives a default creater if you don’t have any creater. | Way(method) Â is not provided by compiler in any case. |
Creater name must be same as the class name. | Way(method) Â name may or may not be same as class name. |
There are a lot of differences between creaters and way(method) s.
Creater Overloading in Java
Creater overloading is a technique in Java in which a class can have any number of creaters
that differ in parameter lists.The compiler differentiates these creaters by taking into account
the number of parameters in the list and their type.
Example of Creater Overloading
class Coding5{
int id; String
name; int
age;
Coding5(int i,String n){
id = i;
name = n;
}
Coding5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+” “+name+” “+age);}
public static void main(String args[]){
Coding5 s1 = new Coding5(111,”ram”);
Coding5 s2 = new Coding5(222,”krishn”,25);
s1.display();
s2.display();
}
}
Output:
111 ram 0
222 krishn 25