Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a constructor without hard coding parameters (coupling)

Tags:

java

I have a method which creates a new object Student and adds it to an array list studentRegister:

public void addStudent(String name, String age)
{
     studentRegister.add(new Student(name, age));
}

it calls the Student class constructor here:

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

This works but it is bad for maintainability as i have to change any additional parameters in both the Student class and the addStudent method. How do I input the parameters at the addStudent stage without having them harcoded in the addStudent method?

like image 215
geo Avatar asked May 25 '26 02:05

geo


1 Answers

just do this:

public void addStudent(Student s)
{
     studentRegister.add(s);
}

And in constructer/ other methods you can call the above method as below:

public Student(String name, String age) 
{
  this.name = name;
  this.age = age;
  addStudent(this); //here is the call to the above method
}
like image 50
Trying Avatar answered May 27 '26 16:05

Trying



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!