方法重载的出现:
当我们使用一个变量时,我们需要对其进行初始化。在java中,构造器就是完成对象的初始化。构造器的名字与类的名字相同,这样子做的好处:
1、可以避免构造器的名字与其他变量的名字相同
2、编译器能够更好的找到构造器。
而默认的构造器的方法单一,无法满足其他情况下的初始化需要,于是便产生了方法名字相同、参数列表不一样的方法重载。参数列表就涉及到参数的类型、参数的个数、参数的顺序。在一般情况,不赞成因参数顺序的不同而造成的方法重载,因为这样子做不利于日后的维护。而其中方法返回值也有不同,但单依靠返回值的不同而区分方法的不同,在调用方法的时候可能会造成困扰。
这样子的做法也可以推广到一般的方法中。
构造器中的方法重载的使用:
public class ConstrutorTest{
String str;
int n ;
char ch;
public ConstrutorTest() {
this("I love you!",999,'b');//调用三个参数的构造器
//this.("I love you!",999);不允许调用两个构造器
System.out.println("I come from Construtor " +
"which have the parameter of blank");
}
public ConstrutorTest(String str) {
this.str = str;
System.out.println("I come from Construtor " +
"which has the parameter of String str");
}
public ConstrutorTest(int n) {
this.n = n;
System.out.println("I come from Construtor " +
"which has the parameter of int n");
}
public ConstrutorTest(String str,int n) {
this.str = str;
this.n = n;
System.out.println("I come from Construtor " +
"which have the parameters of String str,int n");
}
public ConstrutorTest(String str,int n,char ch) {
this(str,n);
this.ch = ch;
System.out.println("I come from Construtor " +
"which have the parameters of String str,int n,char ch");
}
public static void main(String[] args) {
ConstrutorTest ct = new ConstrutorTest();
System.out.println(ct.str);
System.out.println(ct.n);
System.out.println(ct.ch);
}
}
运行结果:
I come from Construtor which have the parameters of String str,int n
I come from Construtor which have the parameters of String str,int n,char ch
I come from Construtor which have the parameter of blank
I love you!
999
b