1、在创建子类对象时,不仅要对自身成员变量初始化,而且还要对父类的成员变量初始化。
2、this() 用来调用本类的构造函数,super() 用来调用父类的构造函数。
3.super()和this() 只能调用一个,并且放在第一个语句。package e4_8;
public class SubObjectInitializeDemo {
public static void main(String[] args) {
B b1 = new B(1, 2, 3);
System.out.println(b1.getA()+" "+b1.getB()+" "+b1.getC());
}
}
class A{
private int a;
public A(){}
public A(int a){
this.a = a;
}
public int getA(){
return a;
}
}
class B extends A{
private int b;
private int c;
public B(){}
public B(int b){
this.b = b;
}
public B(int a, int b){
super(a);//调用类B的父类A的的构造方法。
//this(b);//super(a)和this(b)只能取其一,且必须放在第一行。
this.b = b;
}
public B(int a, int b, int c){
this(a, b);//调用自身的“public B (int a, int b)”构造方法。
this.c = c;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
}
package e4_8;
public class SubObjectInitializeDemo {
public static void main(String[] args) {
B b1 = new B(1, 2, 3);
System.out.println(b1.getA()+" "+b1.getB()+" "+b1.getC());
}
}
class A{
private int a;
public A(){}
public A(int a){
this.a = a;
}
public int getA(){
return a;
}
}
class B extends A{
private int b;
private int c;
public B(){}
public B(int b){
this.b = b;
}
public B(int a, int b){
super(a);//调用类B的父类A的的构造方法。
//this(b);//super(a)和this(b)只能取其一,且必须放在第一行。
this.b = b;
}
public B(int a, int b, int c){
this(a, b);//调用自身的“public B (int a, int b)”构造方法。
this.c = c;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
}