阴影的概念
给出以下代码:
public class A { static final long tooth = 1L; static long tooth(long tooth){ System.out.println(++tooth); return ++tooth; } public static void main(String args[]){ System.out.println(tooth); final long tooth = 2L; new A().tooth(tooth); System.out.println(tooth); } }
你能解释一下影子的概念吗? 另外,主方法的代码中实际使用了什么tooth
?
我知道这是一个非常难看的代码,但丑陋是SCJP书籍作者的标准选择。
阴影作为一个概念并没有什么神奇之处。 简单地说,对名称的引用将始终引用最近的封闭范围内的实例。 在你的例子中:
public class A { static final long tooth#1 = 1L; static long tooth#2(long tooth#3){ System.out.println(++tooth#3); return ++tooth#3; } public static void main(String args[]){ System.out.println(tooth#1); final long tooth#4 = 2L; new A().tooth#2(tooth#4); System.out.println(tooth#4); }
}
我用一个数字注释每个实例,forms为“tooth#N”。 基本上任何已经在其他地方定义的名称的引入都将超出该范围其余部分的早期定义。
当你在这一点上
System.out.println(tooth);
使用类属性( static final long tooth = 1L;
),然后声明一个新的tooth
,它隐藏了类属性,这意味着它被用来代替它。
在tooth
方法中, tooth
变异体作为值传递,它不会被修改,你可以通过执行main
给出:
1 3 2