栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java方法重载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java方法重载

使用方法重载,您将仅使用不同的参数和/或不同的输出来调用“相同的方法”。这使您可以轻松编写具有相同核心功能但具有不同输入参数的方法。例:

public int Sum(int a, int b) {    return a + b;}public double Sum (double a, double b) {    return a + b;}

否则,您将拥有SumInt(…)和SumDouble(…)之类的方法。您还可以使用2个方法,这些方法具有相同的返回类型但输入不同,并且仍然可以轻松使用重载:

public int Sum(int a, int b) {    return Sum(a, b, 0);}public int Sum (int a, int b, int c) {    return a + b + c;}

这样一来,你只有 一个
地方与人的逻辑和所有其他方法只是调用一个方法与所有的逻辑,只能用不同的参数。然后还有构造函数重载。例如,您可以有一个空的构造函数,可以在其中设置一些默认值,也可以有一个构造函数,可以在其中自己设置值:

//Without overloading you'll have to set the properties after instantiating the classpublic MyClass() {    this.PropertyOne = "1";    this.PropertyTwo = 2;}//usage:MyClass instance = new MyClass(); //now theproperties are already set to "1" and 2, wheter you like it or not//here you change the valuesinstance.PropertyOne = "...";instance.PropertyTwo = 0;//With constructor overloading you have thispublic MyClass() {    this("One", 2);}public MyClass(string propOne, int propTwo) {    this.PropertyOne = propOne;    this.PropertyTwo = propTwo;}//usage:MyClass instance = new MyClass("MyValue", 1000);//if you call MyClass() the default values STILL will be set :)

第二种方式给您更多的可能性,不是吗?而且它使更改代码变得更加容易。希望这可以帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483401.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号