#java #constructor #field
#java #конструктор #поле
Вопрос:
Я пытаюсь преобразовать значение поля для конструктора из другого класса в класс.
public class Student {
private String name;
private int streetNum;
private int houseNum;
...
}
Я хочу ссылаться на эти переменные на переменную поля следующим образом:
private Student studentInfo = new Student(name, streetNum, houseNum);
Есть ли способ сделать это? Я не хочу, чтобы переменные поля были статическими.
Ответ №1:
в конструкторах Java могут быть аргументы, поэтому, если вы хотите установить эти переменные, используя эти аргументы, вам нужно сделать что-то вроде этого:
public class Student {
private String name;
private int streetNum;
private int houseNum;
public Student(String name, int streetNum, houseNum){
this.name = name;
/*if you want to use arguments that
have same name has the variables you have
use "this.variable" to specify that you're reffering to the
variables of the class and not the arguments.
the "this" field refferes to the class itself*/
this.streetNum = streetNum;
this.houseNum = houseNum;
}
}