父类有一个无参数的构造方法, 当实例化一个子类之后, 其构造方法也会被调用, 其父类的构造方法也会被调用, 并且父类的构造方法会先被调用, 子类构造方法会默认调用父类的构造方法.
public class AA{
public AA(){
System.out.println("父类构造方法");
}
}
public class BB extends AA{
public BB(){
System.out.println("子类构造方法");
}
}
public static void main(String[] args) {
new AA (); //输出: 父类构造方法
new BB(); //输出: 父类构造方法
}
使用super调用父类构造方法
public class AA{
public int i = 0;
public AA(){
System.out.println("父类构造方法");
}
public AA(int i){
this.i = i;
System.out.println("父类构造方法"+this.i);
}
}
public class BB extends AA{
public int i = 0;
public BB(int i){
super(i);
System.out.println("子类构造方法");
}
public static void main(String[] args) {
new BB(233);
}
//输出: 父类构造方法233
// 子类构造方法
先调用了父类的构造方法, 然后又调用了子类的构造方法.
super调用父类属性值
public class AA{
public int i = 0;
}
public class BB extends AA{
public int i = 10;
public int geti(){
return this.i;
}
public int getfatheri(){
return super.i;
}
}
public static void main(String[] args) {
BB b = new BB();
System.out.println( b.geti()); // 10
System.out.println( b.getfatheri()); // 0
}