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

查看:154
本文介绍了两种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天全站免登陆