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()); } }

6th Oct 2018, 1:56 PM
Strovosky
Strovosky - avatar
8 odpowiedzi
+ 1
where is the constructor?
6th Oct 2018, 2:09 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 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()); } }
6th Oct 2018, 2:33 PM
Strovosky
Strovosky - avatar
+ 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";
6th Oct 2018, 9:46 PM
JavaBobbo
JavaBobbo - avatar
+ 1
Thanks for explaining the keyword "this" 😀
7th Oct 2018, 10:01 PM
Strovosky
Strovosky - avatar
+ 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()); }
7th Oct 2018, 11:23 PM
JavaBobbo
JavaBobbo - avatar
+ 1
You are welcome
7th Oct 2018, 11:33 PM
JavaBobbo
JavaBobbo - avatar
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. 😐
7th Oct 2018, 10:03 PM
Strovosky
Strovosky - avatar
0
Thanks for the tip on private.
7th Oct 2018, 11:27 PM
Strovosky
Strovosky - avatar