tostring()被隐式调用...如何? [英] tostring() is implicitly called... how?

查看:52
本文介绍了tostring()被隐式调用...如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如何隐式调用 toString()?

  class有效负载{私有int权重;公共有效载荷(int w){重量= w;}公共无效setWeight(int w){重量= w;}公共字符串toString(){返回Integer.toString(weight);}}公共课程testpayload {静态void changePayload(Payload p){p.setWeight(420);}公共静态void main(String [] args){有效负载p =新的有效负载(200);p.setWeight(1024);changePayload(p);System.out.println("p是" + p);}} 

解决方案

此行:

  System.out.println("p是" + p); 

使用字符串连接,该字符串连接在第15.18.1节,以:

开头

如果只有一个操作数表达式的类型为String,则对另一操作数执行字符串转换(第5.1.11节)以在运行时生成字符串.

第5.1.11节具有:

任何类型都可以通过字符串转换转换为 String 类型.

...

现在只需要考虑参考值:

  • 如果引用为 null ,则将其转换为字符串"null" (四个ASCII字符n,u,l,l)./p>

  • 否则,转换的执行就好像是通过调用不带参数的引用对象的 toString 方法进行的;但是如果调用 toString 方法的结果为 null ,则使用字符串"null" .

In the following code, how is toString() is implicitly called?

class Payload {
    private int weight;
    public Payload (int w) {
        weight = w; 
    }
    public void setWeight(int w) {
        weight = w; 
    }
    public String toString() {
        return Integer.toString(weight); 
    }
}

public class testpayload {
    static void changePayload(Payload p) {
        p.setWeight(420);
    } 
    public static void main(String[] args) {
        Payload p = new Payload(200);
        p.setWeight(1024);
        changePayload(p);
        System.out.println("p is " + p);
    }
}

解决方案

This line:

System.out.println("p is " + p);

uses string concatenation, which is specified in section 15.18.1 of the JLS, starting with:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

Section 5.1.11 has:

Any type may be converted to type String by string conversion.

...

Now only reference values need to be considered:

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

这篇关于tostring()被隐式调用...如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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