+ 2
how can i use this program without "this" operater
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()); } }
13 Respostas
+ 12
@ashad ,
here u have an object that is "v1" , "this" is used for that object ... when u call method setColor () & u write this.color=c; ... u r associating that color with the object ,
similarily, if u have created the object v2 also , & u call the method , then this will refer to v2
//đ& yes , u can remove "this" keyword ... u know why? ... just because color is an instance variable(non-static) ... it can be different for different objects of the same class .... ie for v1 , color can be red .... for v2 , color can be blue etc & etc
//but will not do that for static member variable ... as it is associated with the class only ... for example ::: private static int speed = 100;
//it will same for every object (v1 or v2) of class vehicle
//hope it helps đâș
+ 22
might some confusion there @csh
//"this" keyword only refers ro the current object , it does not tell anything abt which class or anything like that âș
//no , just some discussion@jamie âș
+ 9
You can omit (remove) the 'this' keyword in the setter function so it becomes instead:
public void setColor(String c) {
color = c;
}
And your Java program will work just fine.
+ 4
but i remember , somebody saying its ok but not to do that, any expert opinion why that guy said like that, and he said like that before java 9 or 8 , I guess
+ 3
just remove "this."
+ 2
hi, let me explain to you. a java developer write classes and add classes(like pakeges) in his project. most of time write class and its not easy to write, especially determine attributes and methods. think like that we write a class and this class have so many variables and methods. variable's name and method's parameter name can be chosen the same name ... in this stuation our mind will confuesed. and also it can be happen another coder want use your class or maintenance your class. Ther is a big problem which variable belongs who ???
"this" keyword help coder and reader. it say this. belong class dont confused any method parameter.
for example
public class vehicle {
private String color;
...
...
...
public void setColor(String color){
this.color = color; // this.color means color belongs to class 2nd color is just paremater name
}
}
+ 2
u r also right @Gaurav Agrawal
your answer absulately right đ
"this" keyword refers current object(instance). i sad that "it belong class" -> i mean instance(object). U know the relation class and object.
In fact we say same think :)
+ 1
then why is this operator is used.
as i thought there must be some reason
+ 1
can you explain me in the single way
+ 1
simple way
+ 1
i hope u understand :)