Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java constructor with no parameter but with class variables

Tags:

java

From the java tutorial I see that a class can have two different constructors with the distinction being the number of arguments provided in each constructor, they also give an example of the no constructor parameter. Based on that information and their example. I have written the class to get a better understanding. I also notice that the fields inside the no param constructor can be changed using getter and setter methods, so I do not see differences with a constructor that has parameters. I have read some question here but they don't address this.

My question: Are there specific cases where such constructor SHOULD be used, if yes what is the reasoning behind it and are there benefits?

public class Course {

    int numberOfStudents;
    String courseName;
    String courseLecturer;

    public Course() {
        this.courseName = "Human Science";
        this.courseLecturer = "Jane Doe";
        this.numberOfStudents = 22;
    }

    public Course(String courseName, String courseLecturer, int numberOfStudents) {

        this.courseName = courseName;
        this.courseLecturer = courseLecturer;
        this.numberOfStudents = numberOfStudents;

    }

    public String getCourseName() {

        return this.courseName;
    } 

    public void setCourseName(String courseName) {

        courseName = this.courseName;
    } 

    public static void main(String[] args) {

        Course courseType2 = new Course("CIV4046F", "Obi", 45);
        System.out.println(courseType2.getCourseName());

    }

}
like image 362
Nobi Avatar asked Jan 29 '23 02:01

Nobi


2 Answers

No, defining default constructors with "realistically looking" too-specialized magic values is not a good idea, it will only cause trouble later on during debugging ("What's wrong with out database, where did this Jane Doe come from?").

Overriding default constructor might make more sense when there are some "canonical default values". For example, if you were modeling fractions, then setting the numerator to 0 and denominator to 1 would give a nice default representation of a zero as a fraction.

like image 79
Andrey Tyukin Avatar answered Feb 07 '23 17:02

Andrey Tyukin


the default parameter constructor is used when the user doesn't affect any value at the instantiation so there is default values that can be used instead of emptiness , and if there is parameters the class use the parameters affected by the user.

like image 27
zouhair Avatar answered Feb 07 '23 19:02

zouhair