this in java
this is a keyword in Java.It can be used inside the method or constructor of Class.Within an instance method or a constructor, this is a reference to the current object
— the object whose method or constructor is being called. You can refer
to any member of the current object from within an instance method or a
constructor by using this.
Here are the points where the keyword this can be used in Java :
- Within the method of current class.
- Within the constructor of current class.
- To refer current class instance variable.
- Passed as arguments to call constructor.
- Passed as arguments to call method.
- To invoke the method of current class.
- To invoke the constructor of current class.
1. Without this
// one class needs to have a main() method
public class HelloWorld
{
public static void main(String[] args)
{
// create an instance of class "OtherClass"
OtherClass myObject = new OtherClass("Hello World!");
// call the method of class "OtherClass"
myObject.display();
}
}
public class OtherClass
{
private String message;
public OtherClass(String message)
{
message = message;
}
public void display(){
System.out.print("message : "+message);
}
}
Output :
message : null
Here the out is null because the name of instance variable (message)and local variable (message) is same . To distinguish this two variable we should use the this keyword . Here are the program .
2. With this
// one class needs to have a main() method
public class HelloWorld
{
public static void main(String[] args)
{
// create an instance of class "OtherClass"
OtherClass myObject = new OtherClass("Hello World!");
// call the method of class "OtherClass"
myObject.display();
}
}
public class OtherClass
{
private String message;
public OtherClass(String message)
{
this.message = message;
}
public void display(){
System.out.print("message : "+message);
}
}
Output :
message : Hello World!
Find us :
Facebook : @apnaandroid
Google+ : Apna Java
Youtube : Android & Java Tutorial
Comments
Post a Comment