Nobi
Nobi

Reputation: 1109

Understanding Java constructor with no parameter but with class variables

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());

    }

}

Upvotes: 4

Views: 13874

Answers (7)

Kushagra Misra
Kushagra Misra

Reputation: 481

One of the many reasons to override default constructor in java is you want to initialize some class level parameters which you are going to processes in different method and those parameter are must to initialize that class.. There are many example in java for these kind of non default constructors for example

BufferedReader br=new BufferedReader(fr)

Where fr is file reader object. If file stream is not passed to buffer reader you cannot use buffer reader class.

Upvotes: 0

nits.kk
nits.kk

Reputation: 5336

Constructor execution results in creation of an object. Once an object is created the user code is not forced to set any parameter before using the object even though there may be setter methods available.

Parametrized constructor and setter methods. Suppose there is a class Duck with a parameter height of type int. You may have a setter method to set the height. Now if an object of Duck is created user code may use this invalid object of Duck (of 0 height). Even though setter method is present but still user code is not enforced to set it before using the created object. To enforce creation of object with necessary life giving parameters Parameterized constructors are needed. The setter methods enables you to modify the states during run time of the application. Based on the modified states the behavior of object can also be modified so they have a different use case but parameterized constructor solves different purpose as I mentioned above.

Default constructor on the other hand provide the user to create the object with states set to default values (these defaults may be defined inside the class while fields declaration itself or in super class or in other constructors or methods invoked by no parameter constructor).

Upvotes: 2

Andrey Tyukin
Andrey Tyukin

Reputation: 44967

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.

Upvotes: 2

Abhishek Singh
Abhishek Singh

Reputation: 246

Your default constructor have no effect on class variables. Instead of initializing class variable where it is declared you should initialize in the default constructor. enter image description here

Upvotes: 0

SrThompson
SrThompson

Reputation: 5748

There is definitely a use case for a default constructor (the one with no arguments) when you want to provide default values for non-final attributes. However, your example is not the recommended approach to provide such defaults. Your attributes should be initialized in the constructor, otherwise you have go around the class to know where the values come from. This would be better

public class Course {
    //You should also keep these private to avoid them being set outside of the class
    int numberOfStudents;
    String courseName;
    String courseLecturer;

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

Upvotes: 2

pecks
pecks

Reputation: 340

you're getting confused because your parameters have the same name as your fields. your no-arg constructor is setting the fields to the values that they have already have been given, which isn't very useful - there's no point in doing this. your constructor with three args sets the fields to the values that you are passing in. so if you want to set the fields to values other than your defaults, you need to use the constructor with three args. otherwise a no-arg constructor will do (although it doesn't need to do anything). note also in Java, if you don't provide a constructor, you get a no-arg constructor for free. but as soon as you write a constructor with arguments, you will have to write a no-arg constructor (if you want one).

Upvotes: 0

zouhair
zouhair

Reputation: 71

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.

Upvotes: 2

Related Questions