方法的重载(overload)
其实在前面已经将这个概念引出来了。
有的时候,当我们已经有了一个带有参数的构造方法,还需要一个不带有参数的构造方法,那么就要声明一个不带参数的构造方法。
重载构成的条件:
方法名相同,但参数类型不同或参数个数不同,才能构成方法的重载。可见,构成条件只与参数有关,与方法的返回类型无关,因为有的方法根本就无返回类型,比如说构造函数就是一个活生生的例子。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Point {
private int x ,y; // 成员变量
public Point() {
x = 1;// 初始化成员变量x
y = 1;// 初始化成员变量y
}
public Point(int a,int b) {
x = a;
y = b;
}
public void output() {// 成员方法
System.out.println("x = "+x);
System.out.println("y = "+y);
}
public void output(int i, int j) {// 成员方法
System.out.println("i = " + i);
System.out.println("j = " + j);
System.out.println("x + i = " + (x + i));
System.out.println("y + j = " + (y + j));
}
public static void main(String[] args) {
Point pt;
pt = new Point(5,5);// 调用带参数的构造函数
pt.output();
pt.output(3, 4);
Point pt2;
pt2 = new Point();// 调用不带参数的构造方法
//pt.x = 10;// 修改值
//pt.y = 20;
pt2.output();
}
}