java方法重载和重载方法_什么是Java重载?

java方法重载和重载方法

Overloading in Java is the ability to define more than one method with the same name in a class. The compiler is able to distinguish between the methods because of their method signatures.

Java重载是在类中定义多个具有相同名称的方法的能力。 编译器能够区分方法,因为它们具有方法签名

This term also goes by method overloading, and is mainly used to just increase the readability of the program; to make it look better. However, do it too much and the reverse effect may come into play because the code looks too similar, and can be hard to read.

这个术语也通过方法重载来使用,主要用于增加程序的可读性。 使它看起来更好。 但是,这样做太多,可能会产生相反的效果,因为代码看起来相似,并且可能很难阅读。

Java重载示例 ( Examples of Java Overloading )

There are nine different ways the print method of the System.out object can be used:

可以使用九种不同方式使用System.out对象的打印方法:

When you use the print method in your code, the compiler will determine which method you want to call by looking at the method signature. For example:

在代码中使用print方法时,编译器将通过查看方法签名来确定要调用的方法。 例如:

A different print method is being called each time because the parameter type being passed is different. It's useful because the print method will need to vary how it works depending on whether it has to deal with a string, integer, or boolean.

每次都调用不同的打印方法,因为传递的参数类型不同。 这很有用,因为print方法需要根据必须处理字符串,整数还是布尔值来改变其工作方式。

有关重载的更多信息 ( More Information on Overloading )

Something to remember about overloading is that you can't have more than one method with the same name, number, and type of argument because that declaration doesn't let the compiler understand how they're different.

关于重载,要记住的一点是,您不能有多个具有相同名称,数字和参数类型的方法,因为该声明无法让编译器了解它们的不同之处。

Also, you can't declare two methods as having identical signatures, even if they have unique return types. This is because the compiler doesn't consider return types when differentiating between methods.

另外,即使两个方法具有唯一的返回类型,也不能将它们声明为具有相同的签名。 这是因为在区分方法时,编译器不会考虑返回类型。

Overloading in Java creates consistency in the code, which helps eliminate inconsistencies, which could lead to syntax errors. Overloading is also just a convenient way to make the code easier to read through.

Java中的重载会在代码中创建一致性,从而有助于消除可能导致语法错误的不一致之处 。 重载也是使代码更易于阅读的一种便捷方法。

翻译自: https://www.thoughtco.com/overloading-2034261

java方法重载和重载方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值