This question already has an answer here:
这个问题在这里已有答案:
- Why are static variables considered evil? 29 answers
为什么静态变量被视为邪恶? 29个答案
How do I get each addresses from each of the objects from my code. The code seems right. But it return only the House2 address, both times. It didn't return the first address.
如何从我的代码中获取每个对象的每个地址。代码似乎是正确的。但它两次都只返回House2地址。它没有返回第一个地址。
public class House {
private static String address;
House ( String addr ) {
address = addr;
}
public static String returnAddress () {
return address;
}
public static void main (String [] args) {
House house1 = new House("house 1 address");
House house2 = new House("house 2 address");
System.out.println( house1.returnAddress());
System.out.println( house2.returnAddress());
}
}
1 个解决方案
#1
Remove the static keyword. A static variable is global, meaning it's shared across all instances of that class, as opposed to a non-static variable, which is specific to each instance itself. When you make the first house, you're setting address to the the first string ("house 1 address"), which is SHARED by all houses, and when you instantiate the second, you're setting address to the second string ("house 2 address"). Accordingly, remove the static keyword from returnAddress()
.
删除static关键字。静态变量是全局的,这意味着它在该类的所有实例之间共享,而不是非静态变量,该变量特定于每个实例本身。当您创建第一个房子时,您将地址设置为第一个字符串(“房屋1地址”),这是所有房屋共享的,当您实例化第二个字符串时,您将地址设置为第二个字符串(“房子2地址“)。因此,从returnAddress()中删除static关键字。
#1
Remove the static keyword. A static variable is global, meaning it's shared across all instances of that class, as opposed to a non-static variable, which is specific to each instance itself. When you make the first house, you're setting address to the the first string ("house 1 address"), which is SHARED by all houses, and when you instantiate the second, you're setting address to the second string ("house 2 address"). Accordingly, remove the static keyword from returnAddress()
.
删除static关键字。静态变量是全局的,这意味着它在该类的所有实例之间共享,而不是非静态变量,该变量特定于每个实例本身。当您创建第一个房子时,您将地址设置为第一个字符串(“房屋1地址”),这是所有房屋共享的,当您实例化第二个字符串时,您将地址设置为第二个字符串(“房子2地址“)。因此,从returnAddress()中删除static关键字。