Java Basics  «Prev  Next»

Adding Access Control in Java - Exercise

Modify the drawing program

Take the code on the previous page for the Shape, Circle, and Square classes and modify it with the following design in mind:
  1. Define the color, x, y, and width variables so that only subclasses can access them.
  2. Define a new constructor for Shape that takes each of these variables so any class can set this data when the object is first created. (Define the appropriate constructors in Circle and Square, as well.)
  3. Modify the Shape, Circle, and Square classes so all their methods can be accessed by any class. This way, Shape, Circle, and Square could theoretically be placed within their own packages.

Caution regarding Public Classes

The Oracle JDK insists that any public class be placed within its own source file. Therefore, if you do try to make these changes and recompile your program to verify it, you will have to divide your source into separate files, each one named after the public class it contains.
Once you have made these changes, copy and paste your new class definitions for Shape, Circle, and Square into the text area below.