在Java中,如何重载方法?
此示例显示根据参数的类型和数量重载方法。
package com.yiibai;
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is " + i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height + " feet tall");
}
void info(String s) {
System.out.println(s + ": House is " + height + " feet tall");
}
}
public class MethodOverloading {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");
// Overloaded constructor:
new MyClass();
}
}
执行上面示例代码,得到以下结果 -
Building new House that is 0 feet tall
House is 0 feet tall
overloaded method: House is 0 feet tall
bricks
示例-2
package com.yiibai;
public class MethodOverloading2 {
void sum(int a, int b) {
System.out.println(a + b);
}
void sum(int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main(String args[]) {
MethodOverloading2 cal = new MethodOverloading2();
cal.sum(200, 130, 260);
cal.sum(20, 30);
}
}
执行上面示例代码,得到以下结果 -
590
50
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。