29 / 51

Scala - Assessment - Declare a class with multiple constructors

A class can have multiple constructors which means its objects can be created with different types of input fields.

For such a class, default constructor doesn't take any field and required constructors are defined inside the body of the class.

Let's declare a class Student having below member fields.

  • name of type String
  • sex of type Char (M / F)
  • grade of type Integer (ex - 1, 2, 3, 4 etc)
  • age of type of Integer (ex - 7, 10, 13 etc)

The Class should have multiple constructors so that using the resulting class, one should be able to instantiate new objects in various ways as shown below:

An object of Student can be created just by name with default values for other fields (sex = F, grade = 5 and age = 12).

var stu = new Student("Dey");

An object of Student can be created just by name and sex with defaut values for other fields (grade = 5 and age = 12).

var stu = new Student("Mack", 'F');

An object of Student can be created by name, sex, grade and age.

var stu = new Student("Doe", 'F', 8, 16);

The class members of the object should be accessible as below:

var name_stu =
var sex_stu =
var grade_stu = stu.grade
var age_stu = stu.age
  • Write the code of the class in Jupyter and press Shift+Enter.

  • Try to create objects of the class in various ways as described and make sure that it works as required.

  • Test that you are able to access the value of member fields using the dot operator.

  • Click on "Submit Answer".