0

How to print a public attribute?

I have just learned Java after python, How do I print the word 'Red' from this code? and what did I do wrong in this code? https://code.sololearn.com/crVXFDL19BKV/?ref=app

10th Oct 2019, 7:08 AM
Steven Sim
Steven Sim - avatar
4 Answers
+ 2
Because color isnt a method, you cant use v1.color("Red") . You have to set it like a normal var using v1.color = "Red" . Then it works fine.
10th Oct 2019, 7:25 AM
Lord HN
Lord HN - avatar
+ 3
You have to create a setter and getter method like this. public class Vehicle { private String color; public void setColor(String color) { this.color = color; } public String getColor() { return color; } } Vehicle v = new Vehicle (); v.setColor("Red"); v.getColor(); And remember variable in class should be always private because of incapsulation.
10th Oct 2019, 7:47 AM
A͢J
A͢J - avatar
+ 1
Lord HN thank you for the answer, I literally copy pasted the code from sololearn and only added the print command, but thank you for straightening things up
10th Oct 2019, 1:01 PM
Steven Sim
Steven Sim - avatar
0
No Problem😁
10th Oct 2019, 1:19 PM
Lord HN
Lord HN - avatar