繁体   English   中英

如果两个对象访问同一个实例变量会发生什么?

[英]what happens if two objects acess the same instance variable?

我已经创建了一个用户定义的 object,它访问一个实例变量和一个方法。然后我创建了一个由 3 个元素组成的数组,其中一个引用变量引用了我最初创建的 object。现在 ZA2F2ED4F8EBC2CBB4DZ21A9 的实例变量会发生什么情况参考引用相同的 object。为什么它的 null 说 ruff?

CODE:
public class Dog{
String name;
public static void main(String[] args){

Dog dog1=new Dog();
dog1.bark();
dog1.name="Brat";


Dog myDogs[]=new Dog[3];
myDogs[0]=new Dog();
myDogs[1]=new Dog();
myDogs[2]=dog1;


myDogs[0].name="Fred";
myDogs[1].name="Marge";

System.out.print("last dogs name is ");
System.out.println(myDogs[2].name);

int x=0;
while(x< myDogs.length){
myDogs[x].bark();
x=x+1;
}



}

public void bark(){
System.out.println(name+" says Ruff");
}


}

OUTPUT:

null says Ruff
last dogs name is brat
Fred says Ruff
Marge says Ruff
brat says Ruff

因为您在设置dog1.name之前调用dog1.bark() ,所以调用dog1.bark()name为 null 。 这就是为什么dog1.bark()打印null作为名称

Dog dog1=new Dog();
dog1.bark();
dog1.name="Brat";

如果你像这样设置dog1.name

Dog dog1=new Dog();
dog1.name="Brat";
dog1.bark();

然后它会打印Brat says Ruff

Issue is you are calling the method dog1.bark() before setting a value for the class property String name,so if you don't initialize a value for a class property before the creation of the object java will automatically assign a default value. So Object references like String name will be initialized with null .So that's why you are getting the output as null for the name.

因此,在第二个代码片段中,您正在创建 object 之后立即分配“Brat”,然后调用 dog1.bark(),因此在这种情况下,您在 bark() function 中的逻辑将更改字符串名称= null -----> 默认值为name = "Brat" ,这就是为什么你会得到一个 output 的 "Brat said Ruff"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM