为什么这个指针指向“马崇拜”而不是“马匹”?

时间:2018-02-07 01:56:02

标签: pointers scope pass-by-value

1   public class Horse {
2      Horse same;
3      String jimmy;
4   
5      public Horse(String lee) {
6         jimmy = lee;
7      }
8   
9      public Horse same(Horse horse) {
10        if (same != null) {
11           Horse same = horse;
12           same.same = horse;
13           same = horse.same;
14        }
15        return same.same;
16     }
17  
18     public static void main(String[] args) {
19        Horse horse = new Horse("youve been");
20        Horse cult = new Horse("horsed");
21        cult.same = cult;
22        cult = cult.same(horse);
23        System.out.println(cult.jimmy);
24        System.out.println(horse.jimmy);
25     }
26  }

当Java解释器运行第22行时,为什么cult.same(horse)返回一个指向“Horse cult”的指针,而不是返回指向“Horse horse”的指针,即相同的名称(同样在其中初始化)第11行指向?

1 个答案:

答案 0 :(得分:0)

由于变量sameif语句中声明,因此无法在if块之外访问它。因此,在return语句中,它会找到same变量cult self。

相关问题