Search code examples
javaprivateaccess-specifier

How do I access a private variable from a method?


currentColor = getCarColor(this.car.color)

Here color is private and getCarColor is a method, how do I access the variable color?


Solution

  • You should not be accessing private variables directly: they are made private for a reason.

    The proper way to do it is to add a public accessor method for the color to the car:

    class Car {
        private Color color;
        // Add this method:
        public Color getColor() { return color; }
    }