使用方法后的Java结果不符合预期 [英] Java result after using a method isn't as expected

查看:107
本文介绍了使用方法后的Java结果不符合预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下snipet代码:

i have the following snipet of code :

class Phone {
    String phoneNumber = "123456789";
    void setNumber () {
        String phoneNumber;
        phoneNumber = "987654321";
    }
}
class TestPhone {
    public static void main(String[] args) {
        Phone p1 = new Phone();
        p1.setNumber();
        System.out.println (p1.phoneNumber);
    }
}

我期待987654321的结果,但我得到了123456789
它就像方法setNumber没有任何效果
任何人都可以帮助我理解

im expecting "987654321" as result, but im getting "123456789" it is like the method setNumber is without any effect can anyone helps me to understand please

推荐答案

您在方法中重新声明phoneNumber变量,遮蔽类中的字段,因此在阴影类字段中将看不到对局部变量所做的任何更改。不要这样做;摆脱重复变量声明,以便在该字段中看到方法中所做的更改。

Your re-declaring the phoneNumber variable inside the method, shadowing the field in the class, and so any changes made to the local variable will not be seen in the shadowed class field. Don't do this; get rid of the repeat variable declaration, so that changes made within the method will be seen in the field.

例如,更改此:

void setNumber () {
    String phoneNumber; // *** this is a local variable, visible ONLY in the method!
    phoneNumber = "987654321";  // this has no effect on the field
}

到此:

void setNumber () {
    // String phoneNumber;
    phoneNumber = "987654321"; // this will change the field!
}

这篇关于使用方法后的Java结果不符合预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆