Access specifiers: public and private data and methods
Learn how to use the keywords public and private, and how to use getter and setter methods to maintain consistent object state.
Instance variables of an object can be accessed using dot notation, just like in Python, Javascript, or C++. Here’s the simple example of defining a Circle
class, which allows Circle
objects to be created. Each circle object has the instance variables x
, y
, and r
:
// include educative's simple graphics library:import com.educative.graphics.*;class Circle {public int x;public int y;public int r;}class CircleTest {public static void main(String[] args) {Circle circ;circ = new Circle();// set values for the instance variables for the circle:circ.x = 100;circ.y = 100;circ.r = 50;Canvas c = new Canvas(200, 200);c.fill("yellow");c.stroke("black");c.circle(circ.x, circ.y, circ.r);}}
We can access the radius of the circle with circ.r
in Java, just like in Python or Javascript, and we’ve done so in the above code.
However, in Java, it is considered bad form to directly access instance variables from methods outside the class. Why?
-
Internal representations change. If I decide later that the radius of the circle should be a double, and that the variable name should be
radius
, I might remove the instance variabler
, breaking every piece of code that depends on it. -
No error checking is performed when modifying an instance variable directly. For example, if I write the code
circ.r = -50
, then the circle is in an inconsistent state.
Setter methods #
If we are not allowed to set the value of r
directly from outside the Circle
class, how should we change the radius of the circle? One way of modifying instance variables is a setter method. Such a method may be called from outside the class, and handles the management of instance variables as needed. For example:
// include educative's simple graphics library:import com.educative.graphics.*;class Circle {public int x;public int y;public int r;public void setRadius(int radius) {if(radius < 0) {throw new IllegalArgumentException("Circle radius must be non-negative.");}this.r = radius;}}class CircleTest {public static void main(String[] args) {Circle circ;circ = new Circle();// set values for the instance variables for the circle:circ.x = 100;circ.y = 100;circ.setRadius(20);Canvas c = new Canvas(200, 200);c.fill("yellow");c.stroke("black");c.circle(circ.x, circ.y, circ.r);}}
Run the above code. Then change the argument in circ.setRadius(20)
to -20, and run the code again. You’ll see that an exception is generated and the code crashes. Good! Now the programmer knows that there is a bug and can fix it.
To generate an error ...