Java -- 函数的 return 类型是 "String" 但它可以 return String 和 int 数据类型

Java -- The return type of a function is "String" but it can return both String and int data types

class Student {
    String name;
    int age;

    public void setInfo(String n, int a) {
        this.name = n;
        this.age = a;
    }

    public String getInfo() { // Notice the "String" data type in this function
        return (this.name + " " + this.age);  // "this.age" is a "int" data type but the function is supposed to be returning only "String" data type, right?
    }
}

public class OOPS {
    public static void main(String args[]) {
        Student s1 = new Student();

        s1.setInfo("John", 24);
        System.out.println(s1.getInfo());
    }
}

这是输出:Click me to see the output

接下来我尝试做的是在函数中用“int”替换“String”。

像这样:

public int getInfo() {      
     return (this.name + " " + this.age); 
}

它抛出这个错误:Click me to see the error

问题是为什么会这样?

您代码中的字符串连接:

return ( this.name + " " + this.age );

… 从您的 int 成员字段 this.age.

隐式生成一个字符串

相当于调用String.valueof:

return ( this.name + " " + String.valueOf( this.age ) );

请参阅 Oracle 免费提供的 Java 教程 中的 Converting Numbers to Strings