两个 Java 方法可以具有相同的名称但返回类型不同吗? [英] Can two Java methods have same name with different return types?

查看:27
本文介绍了两个 Java 方法可以具有相同的名称但返回类型不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个 Java 方法是否可以具有相同的名称和不同的返回类型?方法的返回类型不同,声明的方法名相同.

Can two Java methods have the same name with different return type? The return type of the methods are different and they are declared with the same method's name.

允许吗?

推荐答案

如果两个方法的参数类型相同,但返回类型不同,这是不可能的.来自 Java 语言规范,Java SE 8 版,第 8.4 节.2.方法签名:

If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:

两个方法或构造函数,M 和 N,如果它们具有相同的名称,相同的类型参数(如果有)(第 8.4.4 节),并且在将 N 的形参类型适应于M的类型参数,相同的形参类型.

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

如果两个方法都有不同的参数类型(所以,它们有不同的签名),那么这是可能的.这叫做重载.

If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.

这篇关于两个 Java 方法可以具有相同的名称但返回类型不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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