1

This is related to a Java homework assignment.

I've written a class for creating instances of Course Objects, each course has parameters like course name, max number of students and a room number. However for some of the classes the room is not known. Is there a way to initialize and a Course Object without the room number?

public class ITECCourse {

private String name;
private int code;
private ArrayList<String> students;
private int maxStudents;
private int room = 0;

. . .

//Constructor

public ITECCourse(String courseName, int courseCode, int courseMaxStudents, int room) {
    this.name = courseName;
    this.code = courseCode;
    this.students = new ArrayList<String>();
    this.maxStudents = courseMaxStudents;
    this.room = room;
Kyle D. Hebert
  • 131
  • 1
  • 6

3 Answers3

2

You have a few options:

  1. You could create a second constructor that does not take a room number:

    public ITECCourse(String courseName, int courseCode, int courseMaxStudents)
    
  2. You could change room from and int to an Integer. This would allow a null value.

Either way, you'd want to add a method setRoomNumber() to allow the user to provide that value later.

0

Add a second constructor that doesn't take (or set) the room number.

David Conrad
  • 15,432
  • 2
  • 42
  • 54
0

Yes, you can overload the constructor. As well as the constructor that you have above you can add a new one to the class that would look like this:

public ITECCourse(String courseName, int courseCode, int courseMaxStudents) {
    this(courseName, courseCode, courseMaxStudents, 0);
}

This would then allow you to not have the room default to a certain value in the case that it has not been set.

Another good thing about doing it this way is that by calling the other already existing constructor you're not running into the issue of repeating code everywhere (to set all the values).

See this question for more details on best practices

Community
  • 1
  • 1
Paul Thompson
  • 3,290
  • 2
  • 31
  • 39
  • Thanks for the example. This is what I was thinking of doing based on some reading, but I wasn't sure how to implement it. – Kyle D. Hebert Feb 19 '15 at 19:48