首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么要将一个变量赋给另一个变量呢?

为什么要将一个变量赋给另一个变量呢?
EN

Stack Overflow用户
提问于 2014-10-03 02:43:12
回答 5查看 109关注 0票数 0

我不明白为什么要这样做:

代码语言:javascript
运行
复制
public class Example {
    private String name;
    private String surname;

    Example(String firstName, String secondName) {
        name = firstName;
        surname = secondName;
    }
    // whatever other code goes here
}

我不明白为什么我需要设置name = firstNamesurname = secondName。为什么我不能直接设置namesurname

EN

Stack Overflow用户

发布于 2014-10-03 02:46:23

这些不是相同类型的变量:

  • firstNamesecondName是方法参数。一旦方法结束,这些变量就会从scope
  • name中消失,而surname则是类中的字段。只要该类的实例存在,它们就会一直“附加”到该类的实例上。

下面是一个例子,说明了这意味着什么:

代码语言:javascript
运行
复制
String a = "Hello";
String b = "World";
// For the duration of the constructor, a becomes firstName,
// and b becomes secondName
Example e = new Example(a, b);
// Once the constructor exists, firstName and secondName disappear.
// Resetting a and b after the call is no longer relevant
a = "Quick brown fox jumps";
b = "over the lazy dog";
System.out.println(e.getName()+" "+e.getSurname());

ab的值已经改变,但存储在Example中的值仍然设置为您传递给构造函数的值。

票数 5
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26167426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档