目录
构造器:
1.可以定义一个或多个:方法重载
2.函数名与类名严格相同
3.构造函数的调用只能通过 new xxx()调用,对象名.方法名只能调用一般成员方法
构造器书写建议:
如果要重载多种构造方法,一定要保留书写默认构造方法,注意:一旦重载了构造方法,默认构造方法就不再会生成。
代码书写规则:
BankAccount.java:代码文件
class BankAccount {
}
BankAccount.class:编译文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package test;
class BankAccount {
BankAccount() {
}
}
说明:自动生成了构造器
Test.java:代码文件
package test;
public class Test {
String name;
int score;
public Test(String name, int score) {
this.name = name;
this.score = score;
}
public static void main(String[] args) {
Test test = new Test("陈X仁", 100);
System.out.println(test.score);
System.out.println(test.name);
}
}
Test.class:编译文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package test;
public class Test {
String name;
int score;
public Test(String name, int score) {
this.name = name;
this.score = score;
}
public static void main(String[] args) {
Test test = new Test("陈X仁", 100);
System.out.println(test.score);
System.out.println(test.name);
}
}
说明:没有默认生成原始构造器
构造器链
定义:
假设场景:创建一个正方形的构造函数,正方形有5个参数,现在要写多种构造方法,每种构造方法中用户能传入的参数类型和参数个数各不相同,当用户传递的参数小于5时,我们需要设定默认参数,如果要在每个构造器中都写 this.xx = xx; 来指定属性值的话将无比麻烦,所以我们可以将该构造器链接至该类中的其它指定参数更完全的构造器上,或者链接至父类构造器(类似于构造方法中调用构造方法),节省代码行数,同时增强可维护性。
代码书写规则:
1.只包含子类链
package test;
public class Test {
//构造器1
String name;
int score;
public Test(String name, int score) {
//合法性检验
if (name != "陈XX") {
System.out.println("输入不合法,请重新输入!");
}
switch (score / 10) {
case 0:
case 1:
case 2:
case 3:
case 4:
default:
}
this.name = name;
this.score = score;
}
//构造器2
public Test(int score) {
this("陈XX", score);
}
//构造器3
public Test(String name) {
this(name, 100);
}
//构造器4
public Test() {
this("陈XX",100);
}
//打印方法
public void printValue() {
System.out.println(this.name);
System.out.println(this.score);
System.out.println();
}
//实例化类尝试
public static void main(String[] args) {
Test test1 = new Test("陈XX");
Test test2 = new Test();
Test test3 = new Test(100);
Test test4 = new Test("陈XX",100);
test1.printValue();
test2.printValue();
test3.printValue();
test4.printValue();
}
}
输出结果:
��XX
100��XX
100��XX
100��XX
100
Process finished with exit code 0
2.包含父类链
构造器与可维护性:
如例1可见,多个构造器重载,最终的合理性检验代码只需要存在在某一个构造器中,而这个构造器一般为包含参数最多的构造器,这样代码在维护时,比如合理性检验的规则修改便可以集中在一个代码区完成,减少了人为隐患。