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
We saw that all methods need return types or the word
void for no return type. However, there is one exception: constructors. This is because a constructor is called when an object is created, so it 'returns' the Object itself and cannot return anything else.
All about Constructors
A constructor is created by simply writing a method with the same name as the class itself (including the capitalization). The constructor is usually used to set up the values of variables in the object and run any methods that need to be run on creation. Like any method, a constructor can take any number of parameters. As mentioned, a class can have multiple constructors as long as each one has different parameters.