从另一个类创建类的字段

时间:2016-10-19 00:27:07

标签: java constructor field

我正在尝试将构造函数的字段值从另一个类转换为类。

public class Student {
        private String name;
        private int streetNum;
        private int houseNum; 
...
}

我想将这些变量引用到字段变量中,如下所示:

   private Student studentInfo = new Student(name, streetNum, houseNum);

有办法吗?我不希望字段变量是静态的。

1 个答案:

答案 0 :(得分:0)

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;
  }
}