你的位置:首页 > Java教程

[Java教程]java中变量命名和引用变量的一个坑


这次有两个主题,第一个太简单啦,就是java中变量的命名规则,纯记忆性东西。第二个主题,就是讨论一下对象引用变量的一个注意点。

在看一段代码,如果预测结果正确,就不要往下看啦。

 1 public class Test { 2     public static void main(String[] args) { 3         Test t = new Test(); 4         Test.Dog d1 = t.new Dog(1);//若看不懂,只需看成创建了一个Dog类一个实例变量 5         Test.Dog d2 = d1;//把d1赋值个d2,此时d2的age是不是1? 6         d1.age = 10;//重新为d1的age属性赋值成10 7         //打印结果 8         System.out.println("dog1's age = " + d1.age); 9         System.out.println("dog2's age = " + d2.age);10     }11    12    //为了节省空间能一眼看完,此处写成内部类13     class Dog {14         //为了方便把属性定义为public,实际中最好不要15         public int age;16         public Dog(int age) {17             this.age = age;18         }19 20     }21 }

 

猜猜结果:

猜对没有,为什么没有更改d2的age,d2的age从1变成了10?

基本变量中存的就是实际值,而对象引用变量中存的是一个能找到实际值得数据(可以看成c语言中的地址),所以,当d1赋值d2时,只是把那个能找到实际对象的数据赋值给了d2,内存中只有一个Dog的实例,d1,d2指向同个变量。

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCADcANwDASIAAhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAQFAQIDBgf/xABAEAABAwIDBQUFBQYFBQAAAAABAAIDBBEFITESQVFhcQYTgZGhFCIyscEHI0Ji0SQzQ1Jy4RUWU7LwRGOClML/xAAaAQEAAgMBAAAAAAAAAAAAAAAAAwQBAgUG/8QAKREAAgICAgICAgEEAwAAAAAAAAECAwQREiExQQUTImFRFDKBoUJxkf/aAAwDAQACEQMRAD8ApkRFqShERAEREARE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