-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();
    }
}
  • 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 – Anand Dwivedi Mar 23 '23 at 06:13
  • why type more lines of code when less is enough? – experiment unit 1998X Mar 23 '23 at 06:15
  • You could also take a look at this SO post https://stackoverflow.com/a/19359582/16034206 – experiment unit 1998X Mar 23 '23 at 06: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 – Ajay Rawat Mar 23 '23 at 06:16
  • Programming can get very complicated epecially once you get into generics, Inheritance, and Polymorphism. Not having a constructor will eventually cause issues. It's important that you follow the ideas laid out for OOP. \ – SedJ601 Mar 23 '23 at 06:26
  • Look at ` `You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.` – SedJ601 Mar 23 '23 at 06:27
  • from https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html – SedJ601 Mar 23 '23 at 06:27
  • using a constructor or using methods to set data dependence on the requirement, when you need to initialize with some data or some logics you can use constructors – Hashila Mar 23 '23 at 07:02
  • 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()` ( or`new Student(111, "Karan")`). – Thomas Kläger Mar 23 '23 at 07:38

2 Answers2

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.

Adrian Ng
  • 1
  • 2
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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614