
正文
JAVA中构造函数的参数传递给类中的实例变量
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
class VolcanoRobot1
{ String status;
int speed;
float temperature;
VolcanoRobot1(int speed,float temperature)
{ if(temperature > 660)
{ status = "returning home";
speed = 5;
temperature = 780;
}
}
void showAttributes()
{ System.out.println("Status:" + status);
System.out.println("Speed: "+ speed);
System.out.println("Temperature: "+ temperature);
}
public static void main(String[] args)
{ VolcanoRobot1 robot = new VolcanoRobot1(20,780);
robot.showAttributes();
}
}
以上程序运行结果如下:
class VolcanoRobot1
{ String status;
int speed;
float temperature;
VolcanoRobot1(int speed,float temperature)
{ if(temperature > 660)
{ status = "returning home";
this.speed = speed;
this.temperature = temperature;
}
}
void showAttributes()
{ System.out.println("Status:" + status);
System.out.println("Speed: "+ speed);
System.out.println("Temperature: "+ temperature);
}
public static void main(String[] args)
{ VolcanoRobot1 robot = new VolcanoRobot1(20,780);
robot.showAttributes();
}
}
以上程序的运行结果:
class VolcanoRobot1
{ String status;
int speed;
float temperature;
VolcanoRobot1(int speed1,float temperature1)
{ if(temperature1 > 660)
{ status = "returning home";
speed = 5;
temperature = 60;
}
}
void showAttributes()
{ System.out.println("Status:" + status);
System.out.println("Speed: "+ speed);
System.out.println("Temperature: "+ temperature);
}
public static void main(String[] args)
{ VolcanoRobot1 robot = new VolcanoRobot1(20,780);
robot.showAttributes();
}
}
以上程序运行结果:
以上程序说明:在创建对象的时候,(用new)构造函数的参数在初始化类的实例变量时:
如果构造函数的参数列表的参数名与实例变量的参数名一样时,需要利用“this”来进行指代实例变量;
如果希望将构造函数的参数的值传递给实例变量需要用赋值语句进行传递。







