There is no arg constructor or arg constructor

In my program, I read a file with a fixed length, saved each line in a local variable, and then saved each value in a list of class type arrays. To create an array list object, I used the argument constructor with all the variables. This code demonstrates this below.

String a = "text1";
String b = "text2";
SampleModel sm = new SampleModel(a,b);
ArrayList<SampleModel> sampleList = new ArrayList<>();
sampleList.add(sm);

I find this to be absolutely correct, but my colleague asked me to change it to the no arg constructor and call getters and setters instead. It will look below.

SampleModel sm = new SampleModel();
ArrayList<SampleModel> sampleList = new ArrayList<>();
String a = "text1";
String b = "text2";
sm.setA(a);
sm.setB(b);
sampleList.add(sm);

Is there any reason to prefer the no arg constructor to the argument constructor? (My program has about 15 variables)

+4
source share
5 answers

, .

, , .

Java Bean .

, :

  • . , JavaBeans, , .
  • . Java . , , . , .
  • . , . .
+7

, :

  • .
  • - final.

, , , , . , , . , , , . , , , Builder, .

+2

, , ( , , , ); , set.

, , " " . , , , .

:

public SampleModel(String a, String b)
{
    this.a = a;
    this.b = b;
}

, .

+1

, , , , . Double Brace Initialization:

String a = "text1";
String b = "text2";
SampleModel sm = new SampleModel() {{
    setA(a);
    setB(b);
}};
ArrayList<SampleModel> sampleList = new ArrayList<>() {{
    add(sm);
}};
0

: ""

. , , . , , -, , . , , ; , , . , , . - , , , . , , , , , . , . " " , , , . . " ", , , . , " ". . . , . , .

0
source

Source: https://habr.com/ru/post/1628554/


All Articles