Java 当类的属性与形参的名字相同时

来源:互联网 发布:识别颜色的软件 编辑:程序博客网 时间:2024/05/16 07:56

当类的属性和类方法的形参名字相同时,类方法里面的变量是指向类属性还是类方法的形参呢?

这是我刚刚偶尔发现的问题,特地研究了一下。

例如,我现在写一个Test类:(注意:这里没有用this.count,因为this.count是肯定指向类属性的。)

<span style="font-size:18px;">public class Test {public static void main(String[] args) {SecondClass secondClass=new Test.SecondClass(100);System.out.println(secondClass.count);System.out.println(secondClass.second);}static class SecondClass{int count=1;int second=0;public SecondClass(int count) {count=count;//左部count是哪个?右部count又是哪个?second=count;//调用的是哪个count?}}}</span>

当形参编程mCount的时候呢?

static class SecondClass{int count=1;int second=0;public SecondClass(int mCount) {count=count;second=count;}}

第一段代码的运行结果是:

count=1
second=100

得到的结果是,类属性count并没有被类方法调用,而second=count;语句调用的是形参。

第二段代码的运行结果是:

count=1
second=1

得到的结果说明,在没有类属性跟类方法的形参重名的情况下,调用的才是类属性。

所以,在重名情况下,类方法的形参优先级比类属性更高!这就告诫我们,当调用类属性的时候,尽量使用this.变量!这样才不易造成混乱…保持良好的变成习惯,嗯!

0 0
原创粉丝点击