Programming in Java on Your Computer
- Classes and Objects in BlueJ
- Trying out Code in BlueJ
- The Code for Creating and Using Objects
- Source Code and Methods
- Accessors and Mutators
- Constructor Code
- Class Code
- Simple Debugging
- Interactive Picture
- Refactoring Code with Inheritance
Premium Content - Free Preview
In the previous node, you used the Circle Class without touching any of its code. In this node, we'll look at its actual code and make some changes.
This is the beginning of the Circle Class:
Below the Class declaration, the instance variables, which hold data about the Object and are available to all its code, are declared. In this case, they store information about the position and appearance of the Circle.
The constructor appears under the instance variables and is used to set up their initial values. A constructor is just a method with the same name as the Class that runs when an instance of the Class is created.
Currently, Circle's constructor just assigns hard-wired values (like a diameter of 30) to the variables, instead of allowing the variables to be set. Also, the Circle is not visible when created, but requires another call to the method
makeVisible() to show up.
It would be useful if you could set different initial values for the Circle. Create a new constructor that takes in parameters to set the values of
color. To make the Circle visible on creation, call
makeVisible() at the end of the constructor.