Can I call the Set method inside the constructor

I have several installation methods given and using the constructor to initialize their values ​​as follows. It works, but I'm worried about whether this is the usual Java convention for this (is it okay to call the set method inside the constructor?).

An alternative way I can think of is to call an empty constructor and call the set method one by one in the main method to set the value. I find this second method tedious. Please advice if what I have done is fine / under the Java convention or if there is a better way to do this. Tell me if I need to send more code to make my question clearer. I can post it all if that makes sense. Thanks.

public Person(String foreName,String surName, int age, double height, String gender){
        personCount++; 
        setForeName(foreName);
        setSurName(surName);
        setAge(age);
        setHeight(height);
        setGender(gender); 
    }
+4
source share
7 answers

This is not just a matter of taste. If setXXX()there is no additional logic in the methods , the convention should assign attributes directly in the constructor:

this.foreName = foreName;
this.surName = surName;

... Etc. But if setXXX()there is additional logic in the methods , you should use them as needed. Let's say a call to the registration logic or similar:

public void setForeName(String pForeName) {
    log.info("setting new foreName value: " + pForeName);
    this.foreName = pForeName;
}

, setForeName() ? , setXXX() ( , JIT). , , , , .

+4

this , , :

public Person(String foreName,String surName, int age, double height, String gender){
    personCount++; 
    this.foreName = foreName;
    //same goes for the rest of the params
}
+8

, , , . , , , - , , , . .

Java- 17

, . , . , . , , , .

+3

set . , this.var = var, .

+1

. , , .

+1

set ?

private String foreName;
private String surName;
private int age;
private double height;
private String gender


public Person(String foreName,String surName, int age, double height, String gender){
        personCount++; 
        this.foreName = foreName;
        this.surName = surName;
        this.age = age;
        this.height = height;
        this.gender = gender; 
    }

/// setter and getter methods of above private variables..
0

, , , , ( main), . , . , , , , , / , ...

-2

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


All Articles