class A{
A(){
this("1","2");
}
A(String s){
System.out.print(s);
}
A(String s1,String s2){
this(s1+s2);
}
}class B extends A{
B(){
super("4");
}
B(String s){
System.out.println(s);
}
B(String s1,String s2){
this(s1+s2+"3");
}
}public class test {
public static void main(String[] args) {
B b = new B("test"); }}
A(){
this("1","2");
}
A(String s){
System.out.print(s);
}
A(String s1,String s2){
this(s1+s2);
}
}class B extends A{
B(){
super("4");
}
B(String s){
System.out.println(s);
}
B(String s1,String s2){
this(s1+s2+"3");
}
}public class test {
public static void main(String[] args) {
B b = new B("test"); }}
super()来构造父类(必需是第一条语句),若是不写的话,默认就调用父类的无参构造方法。
在构造器中,如果为this添加了参数列表,将产生对符合此参数列表的某个构造器的明确调用。
体会一下A类的三个构造器。
在子类构造方法的【第一行】会有三种情况
(1)this(有入参or无入参),作用:调用同类其他的构造方法
(2)super(有入参无入参),作用:调用父类的构造方法
(3)不写this(有入参or无入参)和super(有入参无入参),就会默认super(),作用:调用父类无参构造B(String s){
System.out.println(s);
}
第一行不是执行System.out.println(s);而是上面的第三种情况,缺省的super();所以执行
A(){
this("1","2");
}
会调用
B(String s){
super(); //--1 这里隐式调用A的无参构造方法,LZ可以试着把A的无参构造方法去掉,会发现无法编译
System.out.println(s);
}--1会调用
A(){
this("1","2"); // --2
}--2会调用
A(String s1,String s2){
this(s1+s2); // --3
}--3会调用
A(String s){
System.out.print(s);
}所以--3打印 12
然后回到--2,然后回到--1,然后打印B(String s)构造方法的"test"
所以结果就是12test
A(){
this("1","2");
}A(String s){
System.out.print(s);
}A(String s1,String s2){
this(s1+s2);
}
}class B extends A{
B(){
super("4");
}
B(String s){
System.out.println(s);
}
B(String s1,String s2){
this(s1+s2+"3");
}
}public class test {
public static void main(String[] args) {
B b = new B("test");//子类B调用子类B的有参构造方法,B(String s){System.out.println(s);}
//打印test,而楼主忽略了一定,由于子类是从父类继承的,若想构造子类,所以得先构造父类,而规定当子类的构造方法中没有显示的调用父类的构造方法时,默认调用父类的无参构造方法,所以先执行A(){
this("1","2");},而this代表当前对象的引用,是A类对象,相当于调用了A(String s1,String s2){
this(s1+s2); }方法,而s1+s2是由俩个字符串并连接起来,即“12”,变成了this(“12”),接着就调用了A(String s){System.out.print(s); }方法,打印出s,即结果中多余的12,后面的不用说了吧
}
}}