Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Constructor - why not just initialize the variables?

Hi all, I'm having some trouble getting my head around the necessity of a constructor in Java. If I take the following code:

package exams;

public class StudentResults {

Private String Full_Name; Private String Exam_Name; Private String Exam_Score; Private String Exam_Grade;

StudentResults() { Full_Name = "No Name Given"; Exam_Name = "Unknown"; Exam_Score = "No Score"; Exam_Grade = "Unknown"; } }

I'm unsure what would be the difference between just doing this:

package exams;

public class StudentResults {

Private String Full_Name = "No Name Given"; Private String Exam_Name = "Unknown"; Private String Exam_Score = "No Score"; Private String Exam_Grade = "Unknown";

}

Thanks

I'm sorry about the formatting, it looked good when I posted it!

1 Answer

In this case, they would work the same. But as a practice, the second method can have some problems going forward. Imagine that StudentResults was inherited from, like so.

public class StudentResults {

    protected String Full_Name = "No Name Given";
    protected String Exam_Name = "Unknown";
    protected String Exam_Score = "No Score";
    protected String Exam_Grade = "Unknown";

}

public class PerfectStudentResults extends StudentResults {

  public PerfectStudentResults()
  {
    Exam_Score = "100";
    Exam_Grade = "A+";
   }
  public String getExamName() throws Exception {
    if(Exam_Name == null) {
      throw new Exception("Exam not set!"); //This code will never trigger, causing confusion.
    }
  }
}

Somebody without access to the code for StudentResults might assumed they've subclassed it correctly, and since they didn't set the Exam_Name variable, it should be null, but their error handling code won't trigger, because it won't be null.

While the functionality for the most part is the same, for these special cases, it is considered best practice to initialize/assign instance variables in the constructor.

Thank you Samuel, I'm afraid I don't understand when you say "they didn't set the Exam_Name variable, it should be null" as even if it was set to the same Exam_Name = "Unknown" in the constructor wouldn't it also fail?

No, unless explicity called in the subclass constructor, the superclass constructor isn't called.