- Java 编程示例
- 示例 - Home
- 示例 - Environment
- 示例 - Strings
- 示例 - Arrays
- 示例 - Date & Time
- 示例 - Methods
- 示例 - Files
- 示例 - Directories
- 示例 - Exceptions
- 示例 - Data Structure
- 示例 - Collections
- 示例 - Networking
- 示例 - Threading
- 示例 - Applets
- 示例 - Simple GUI
- 示例 - JDBC
- 示例 - Regular Exp
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用资源
- Java - 快速指南
- Java - 实用资源
如何在 Java 中重载方法
问题描述
如何重载方法?
解决方案
此示例显示了根据类型和参数数量重载方法的方式。
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 MainClass {
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
以下是方法重载的另一个示例
public class Calculation {
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[]){
Calculation cal = new Calculation();
cal.sum(20,30,60);
cal.sum(20,20);
}
}
以上代码示例将产生以下结果。
110 40
java_methods.htm
广告