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:

  1. Open up the terminal by clicking on View > Show Terminal.
  2. 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:

  1. Create a new Staff instance using the "new" action without parameters.
  2. 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 student1) .
  3. 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!

Creating Objects

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:

Staff staff1;

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)

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


Contact Us
Sign in or email us at [email protected]