Constructor Code


Collapse Content

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.

source code

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.

Setting up the Instance Variables
We saw that instance variables could be accessed and modified by methods. To set up their values when an Object is created, you can use a constructor. For example, in the Student class's second constructor, SID is assigned a value passed in when the Object is created.

Task
In the second constructor in the Student class, add a new parameter and assign its value to GPA.

To see if you did it successfully, compile your code and create a new Student object that takes in those parameters. (You can then inspect your object to see its variable values, which should include GPA.)

Challenge

In a previous challenge, you created a Car using a Class that already had a constructor. In this challenge, do the reverse: create 2 constructors for the Car class.

The first constructor should take one String parameter and assign its value to the color variable.

The second constructor should take in two parameters, a String and a boolean. It should assign the String to color, and the boolean to the sunroof variable.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Create the header for a constructor of the class Blob that takes in one parameter: an integer named num. The constructor should consist of 3 words, and you should leave off the { after it.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

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