+ 1

What is the point of the private variable in the following code?

public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } // Setter public void setColor(String c) { this.color = c; } } This code was in one of the constructor modules in the Java course on SoloLearn. What is the function of private String color; ? Why is it used?

7th May 2017, 2:53 AM
Kaien Yang
Kaien Yang - avatar
1 Antwort
+ 1
In this example this is no practical reason to declare private class members. But because it is tutorial code - it shows you the way how you should write code if you would work with some complex project. Setting variable in class not always consists of one line of code like "vehicle.color = "red";". Sometimes you would want to validate incoming data or alter some other data if needed.Let's say you want to return error if you try to set "transparent" color for a car - you should place this check in setColor method instead of placing it in all places where you set vehicle.color. This is called an "incapsulation", it is one of main concepts of object-oriented programming and it helps you to better organize your code.
7th May 2017, 3:05 AM
Jeth
Jeth - avatar