[英]How do I properly reference the variable from another method in java?
我不知道我应该如何引用 .toString() 方法中的变量。 我一直在研究如何做到这一点。 它是公开的,所以我不明白为什么它没有被共享。 导入 java.util.Scanner;
class Donation {
public static void main(String[] args) {
Donation uw1 = new Donation("University of Washington", 600.75, true);
Donation uw2 = new Donation("University of Washington", 40, true);
Donation sj = new Donation("Snap Judgment", 30, false);
Donation tal = new Donation("This American Life", 40, true);
Donation mc = new Donation("Microphone Check", 99.99, false);
System.out.println(uw1.toString());
System.out.println(uw2.toString());
System.out.println(sj.toString());
System.out.println(tal.toString());
System.out.println(mc.toString());
}
public Donation(String organization, double amount, boolean tax) {
double v= amount;
String org = organization;
boolean b= tax;
}
public String toString(){
if (!v){
return "$"+v+": "+org;
}
else if (b) {
return "* $" + v + ": " + org;
}
else{
return "error";
}
}
您在构造函数中设置局部变量:
public Donation(String organization, double amount, boolean tax) {
double v= amount;
String org = organization;
boolean b= tax;
}
你知道吗,因为这些变量只存在于构造函数中,一旦构造函数结束,变量就会随之消失,这就是问题的症结所在。 相反,在构造函数之外和类中声明这些变量。
public class Donation {
private double v;
private String org;
private boolean b;
然后是的,在构造函数中设置字段但不要重新声明它们。
public Donation(String organization, double amount, boolean tax) {
v= amount;
org = organization;
b= tax;
}
然后,您可以在 toString 方法中使用这些字段保存的值。
您不能跨方法共享变量,但是您可以使用字段来执行此操作。 您可以在构造函数中分配这些字段,替换您现在在那里定义的变量,然后在toString()
方法中引用这些字段。
在函数内声明的变量是“局部变量”。 它们的生命周期是方法的执行。
所以v
、 org
和b
只存在于你的Donation
构造函数中。 当您调用 toString 时,它们已不存在
要使变量的生命周期与对象的生命周期相同,您需要在对象上创建一个字段。
class Donation {
private final double v;
public Donation(double value) {
v = value;
}
public toString() {
return "$" + v;
}
}
v
是私有的和最终的。 这意味着在创建对象之后就不能再更改了,这样可以更容易地思考您的对象的行为方式,并且在您的类之外无法看到,这意味着您可以在不影响其他类的情况下更改您的类使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.