0
What's the problem with the Object here?
public class Car { String color; public String getColor() { return color; } public void setColor (String name) { this.color=name; } } class DriverUniform { public static void main (String[]args) { Car look = new Car("Red"); System.out.println(look.getColor()); } }
8 Réponses
+ 1
where is the constructor?
+ 1
Thanks, that was totally helpful. ☺
I just added it.
public class Car {
String color;
Car (String name) {this.setColor(name);}
public String getColor() {
return color;
}
public void setColor (String name) {
this.color=name;
}
}
class DriverUniform {
public static void main (String[]args) {
Car look = new Car("Red");
System.out.println(look.getColor());
}
}
+ 1
I would use this if i were you:
class Car {
String color;
Car (String name) {
color = name;
}
public String getColor() {
return color;
}
}
There is no need to use this keyword, only if the instance variable and the parameter got the same name, so java know which variable that is local and instance variable. Example:
class Car {
String color;
Car (String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
Also use private access modifiers ( private String color; ) so only your method can return the color, else if you dont do it you can change it with your reference variable like this:
look.color = "blue";
+ 1
Thanks for explaining the keyword "this" 😀
+ 1
Na there is no need to use set because you pass the value in your constructor.
If you wanna use the set you can do it like this:
class Car {
private String color;
// use private so only your set and get method can set the color
// the get method will return the color in the output
public String getColor() {
return color;
}
// and the set method, so you can set the value
public void setColor(String color){
this.color = color;
}
}
public static void main (String[]args) {
Car c1 = new Car();
c1.setColor("red");
System.out.println(c1.getColor());
}
+ 1
You are welcome
0
If I use the way you suggest then I shouldn't use a setter, do I?
I tried to do it that way but something might've gone wrong. 😐
0
Thanks for the tip on private.