+ 1
Why this keyword is used
Even i omitted this keyword in this program the program runs without any error public class Vehicle { private String color; // Getter public String getColor() { return color; } // Setter public void setColor(String c) { this.color = c; } } class Program { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.setColor("Red"); System.out.println(v1.getColor()); } } rate my question if this question is good
9 Answers
+ 4
this is reference to a current object which u r using
this keyword is passed implicitly even if don't mention.
one of the use of this keyword is suppose say if fuction parameter is same as class variable they u have to use this keyword
public void setColor(String color){
this.color = color;
}
this use to avoid error
+ 2
this keyword can be used to refer to any member of the current object from within an instance Method or a constructor.
+ 2
private String a="class variable";
public void doSomething(){
String a = "local variable";
System.out.println (a);
System.out.println (this.a);
}
Try to run this code and see the output. If we don't have "this" keyword, we couldn't print "class variable".
+ 1
What keyword are you talking about
0
"this" keyword
0
we use variable's value in other class for using this keyword it is simple to use like: this.a,this.b
0
this keyword indicates the current object of the class, as you know this never be used with static variable/Attribute because it's memory allocation type is static.
n this used only for dynamic type of memory blocks/objects. now at the run time may be there are several objects/instances of current class, to identify and accessing Attributes and methods of the current object, we use 'this' keyword.
0
this key word is an implicit pointer to the object ur currently using since ur code runs with in a particular object itself it runs without this keyword.
0
this is like an object created for that class implicitly.. so using 'this' we can access the attributes and behaviour inside the class