-2

guys I am learning Java recently I just finished the concept of Constructor. So what I understand is that Constructors are used to initialize instance variable or objects but we can use methods to do that same task of initializing instance variable can anyone help me understand what exactly we use constructors

//This is my code I tried to initialize instance variable using methods instead of constructors
class Student {
    int rollno;
    String name;

    void insertRecord(int r, String n) {
        rollno = r;
        name = n;
    }

    void displayInformation() {
        System.out.println(rollno + " " + name);
    }
}

public class TestStudent4 {
    public static void main(String args[]) {
        Student s1 = new Student();
        Student s2 = new Student();
        s1.insertRecord(111, "Karan");
        s2.insertRecord(222, "Aryan");
        s1.displayInformation();
        s2.displayInformation();
    }
}
9
  • To initalize something while creating class object is use of constructor initialization whereas method invocation is after class object creation and should contain business logic Commented Mar 23, 2023 at 6:13
  • why type more lines of code when less is enough? Commented Mar 23, 2023 at 6:15
  • You could also take a look at this SO post stackoverflow.com/a/19359582/16034206 Commented Mar 23, 2023 at 6:16
  • okay but I can also initialize my class variable using a method instead of creating a constructor right ok I understood thank you all for giving your response Commented Mar 23, 2023 at 6:16
  • 1
    As you found out you could use a method as well as a constructor. But: the users of your class can forget the call an initialization method. They can however never forget to call the constructor, because the constructor call is implicitly done when you write new Student() ( ornew Student(111, "Karan")). Commented Mar 23, 2023 at 7:38

2 Answers 2

0

This as your reference:

public class Student {
private int rollNumber;
private String name;

public Student(int rollNumber, String name) {
    this.rollNumber = rollNumber;
    this.name = name;
}

public int getRollNumber() {
    return rollNumber;
}

public void setRollNumber(int rollNumber) {
    this.rollNumber = rollNumber;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public void displayInformation() {
    System.out.println(rollNumber + " " + name);
}
}

public class TestStudent {
    public static void main(String[] args) {
        Student s1 = new Student(111, "Karan");
        Student s2 = new Student(222, "Aryan");
        s1.displayInformation();
        s2.displayInformation();
    }
}

  • Or you do not have to use getters or setters if ure using Lombok, just use @Data annotation in Spring.

while it is true that you could use a method to initialize instance variables, constructors are a more natural and convenient way to do so, and have additional benefits such as automatic invocation, clear syntax, and the ability to enforce initialization constraints.

Sign up to request clarification or add additional context in comments.

Comments

0

One important feature that can be implemented using constructors but can NOT be implemented with "normal methods" is to provide invariants:

It's very useful if a class can guarantee certain properties of all its instances (sometimes these are called "invariants").

For example, you could have a Person class that guarantees that givenName and lastName will always have valid, non-null, non-empty values (which is absolutely not true in the real world, by the way, but let's pretend that the world is simple for a second).

You could do that with a constructor that takes the parameters and verifies that they are valid:

public class Person {
    private final String givenName;
    private final String lastName;
    
    public Person(String givenName, String lastName) {
        this.givenName = verifyValidName(givenName);
        this.lastName = verifyValidName(lastName);
    }

    private static String verifyValidName(String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("name is null or empty");
        }
        return name;
    }
    
    // getters
}

Note that in a real, current codebase this should almost certainly be a record instead of a regular class, but that doesn't fundamentally influence the answer and new developers might not yet know record classes.

With this code any code that uses a Person object (independent of whether it created it on its own or it got passed from somewhere else) knows that the two fields will be non-null. There's no need to pepper person.hasValidNames() calls all throughout your code, because you know that no Person can exist where givenName is null.

If you instead initialized the fields in a normal method, then the default constructor would set the fields to null. That's not the end of the world itself, but it means that code that gets passed from anywhere else needs to consider the option that either one of those fields could be null, which potentially adds a lot of complexity.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.