为什么这不会引发 NullPointerException?
以下代码的 Nead 说明:
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample.append("B");
System.out.println(sample);
这将打印,以便证明和对象引用相同的内存引用。B
sample
referToSample
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
sample.append("A");
referToSample.append("B");
System.out.println(referToSample);
这将打印,这也证明了这一点。AB
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
referToSample.append("A");
System.out.println(sample);
显然,这将抛出,因为我正在尝试调用空引用。NullPointerException
append
StringBuilder sample = new StringBuilder();
StringBuilder referToSample = sample;
referToSample = null;
sample.append("A");
System.out.println(sample);
所以这是我的问题,为什么最后一个代码示例没有抛出,因为我从前两个例子中看到和理解的是,如果两个对象引用同一个对象,那么如果我们改变任何值,那么它也会反映给其他对象,因为两者都指向相同的内存引用。那么,为什么这条规则在这里不适用呢?如果我分配到 referToSample,那么 sample 也应该是 null,它应该抛出一个 NullPointerException,但它没有抛出一个,为什么?NullPointerException
null