【问题标题】:Creating field for class from another class从另一个类创建类的字段
【发布时间】:2016-10-19 00:27:07
【问题描述】:
我正在尝试将构造函数的字段值从另一个类变成一个类。
public class Student {
private String name;
private int streetNum;
private int houseNum;
...
}
我想像这样将这些变量引用到字段变量:
private Student studentInfo = new Student(name, streetNum, houseNum);
有办法吗?我不希望字段变量是静态的。
【问题讨论】:
标签:
java
constructor
field
【解决方案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;
}
}