重載的展現形式
重載的實際意義:方法重載的實際意義在于調用者隻需要記住一個方法名就可以調用各種 不同的版本,來實作各種不同的功能
public class Point {
int x; // 用于描述橫坐标的成員變量
int y; // 用于描述縱坐标的成員變量
// 自定義無參構造方法
Point() {}
// 自定義有參構造方法
Point(int x, int y) {
this.x = x;
this.y = y;
}
// 自定義成員方法實作特征的列印
void show() {
System.out.println("橫坐标是:" + x + ",縱坐标是:" + y);
}
// 自定義成員方法實作縱坐标減1的行為
void up() {
y--;
}
// 自定義成員方法實作縱坐标減去參數指定數值的行為
void up(int y) {
this.y -=y;
}
public static void main(String[] args) {
// 2.使用有參方式構造對象并列印特征
Point p2 = new Point(3, 5);
// 3.調用重載的成員方法
p2.up();
p2.show(); // 3 4
p2.up(2);
p2.show(); // 3 2
}
}
code
/*
程式設計實作方法重載主要形式的測試
*/
public class OverloadTest {
// 自定義成員方法
void show() {
System.out.println("show()");
}
void show(int i) { // ok 展現在方法參數的個數不同
System.out.println("show(int)");
}
void show(int i, double d) { // ok 展現在方法參數的個數不同
System.out.println("show(int, double)");
}
void show(int i, int j) { // ok 展現在方法參數的類型不同
System.out.println("show(int, int)");
}
void show(double d, int i) { // ok 展現在方法參數的順序不同
System.out.println("show(double, int)");
}
/*
void show(double a, int b) { // error 與參數變量名無關
System.out.println("show(double, int)");
}
*/
/*
int show(double d, int i) { // error, 與傳回值類型無關
System.out.println("show(double, int)");
}
*/
public static void main(String[] args) {
// 1.聲明OverloadTest類型的引用指向該類型的對象
OverloadTest ot = new OverloadTest();
// 2.調用show方法
ot.show();
ot.show(66);
ot.show(66, 3.14);
ot.show(66, 118);
ot.show(3.14, 118);
//ot.show(3.14, 66);
}
}