Java编程思想读书笔记_第二章

java对于将一个较大作用域的变量“隐藏”的场景会有保护:编译告警。比如:

1 int x = 5;
2 {
3     int x = 6;
4 }

但是对于类中方法的局部变量和类成员变量确是可以重名的,比如

 1 class Test {
 2     int x = 4;
 3     String s = "hello";
 4     
 5     void show() {
 6         int x = 5;
 7         System.out.println(this.x);
 8         System.out.println(x);
 9         System.out.println(s);
10     }
11     public static void main(String[] args) {
12         new Test().show();
13         new Dog().eat();
14     }
15 }
16 
17 class Dog {
18     void eat() {
19         System.out.println("eat");
20     }
21 }

类Test中的show方法中的int x就可以和类成员变量int x重名,而且如果不加this.x明确指示使用类成员变量的话默认就使用的是局部变量。

posted @ 2017-05-28 16:01  Ren.Yu  阅读(153)  评论(0编辑  收藏  举报