[英]what happens if two objects acess the same instance variable?
i have created an user defined object which accesses an instance variable and a method.Then i created an array of of 3 elements in which one reference variable has a reference to object that i initially created.now what happens to instance variable of class if both references refer to same object.why its null says ruff??我已经创建了一个用户定义的 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
Because you are calling dog1.bark()
before setting dog1.name
, so name
is null when calling dog1.bark()
.因为您在设置
dog1.name
之前调用dog1.bark()
,所以调用dog1.bark()
时name
为 null 。 That's why dog1.bark()
prints null
for name这就是为什么
dog1.bark()
打印null
作为名称
Dog dog1=new Dog();
dog1.bark();
dog1.name="Brat";
If you set dog1.name
before like this如果你像这样设置
dog1.name
Dog dog1=new Dog();
dog1.name="Brat";
dog1.bark();
Then it will print Brat says Ruff
然后它会打印
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. 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.
So in the second code snippet what you are doing is you are assigning "Brat" right after the object creation then you are calling the dog1.bark(),so in this situation your logic inside the bark() function will change the String name = null -----> default value to name = "Brat" ,that's why you are getting an output of "Brat says Ruff"因此,在第二个代码片段中,您正在创建 object 之后立即分配“Brat”,然后调用 dog1.bark(),因此在这种情况下,您在 bark() function 中的逻辑将更改字符串名称= null -----> 默认值为name = "Brat" ,这就是为什么你会得到一个 output 的 "Brat said Ruff"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.