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

10/10/2019 7:08:26 AM

Steven Sim

4 Answers

New Answer

+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.

+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.

+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

0

No Problem😁