How to print a public attribute? | SoloLearn: Learn to code for FREE!


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?

10/10/2019 7:08:26 AM

Steven Sim

4 Answers

New Answer


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.


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.


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


No Problem😁