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
The Code for Creating and Using Objects
Premium Content - Free Preview
Viewing the Code
Previously, you created Objects and called their methods using BlueJ's visual interface. When you did this, BlueJ would create and execute code that corresponded with your action.
To view the actual code that gets created you just need to:
- Open up the terminal by clicking on View > Show Terminal.
- With the Terminal selected, click on Options > Record method calls.
You can now repeat the same actions that you did in Objects in BlueJ, but this time you can see what code gets created:
- Create a new Staff instance using the "new" action without parameters.
- Create a new Student instance using the new action that takes 3 parameters. Fill it in however you want (though you should keep the name
- Invoke the getStudentID() method from the Student instance that you just created.
When you're done, you should see something like this:
Let's find out what these lines of code mean!
In the previous module you saw how to declare variables and assign them to values. For example you could type:
int num; num = 11;
Or alternatively you could declare and assign it in one line:
int num = 11;
You can do a similar thing when creating Objects. You declare the type and name of the Object variable:
Note that instead of declaring a primitive type (like
int), you declare the Class (with a capital letter) that the Object belongs to.
Once you declared an Object variable, you can assign it an object:
staff1 = new Staff();
This is something new, since you are creating a new Object. This is done with the
new keyword. The
staff1 variable will now point to this new Staff Object.
Notice there are parentheses at the end of the code to create an Object. Parentheses are used in Java whenever a method is called. In this case, the parentheses represent the call to the constructor, a method that runs when an object is created. Constructors automatically set up certain values in an object. Some constructors have parameters, which are passed (i.e. assigned) inside the parentheses.
The declaration and assignment can again be done in one line of code, even though it now includes creating and setting up an object:
Staff staff1 = new Staff();
(hover above for more info)