java构造函数的继承需要注意一下几点:
1.子类只继承父类的默认构造函数,如果父类没有默认构造函数,那子类不能从父类那继承任何构造函数;
2.子类从父类那里继承来的默认构造函数不能成为自己的默认构造函数;
3.在创建子类对象的时候,首先调用父类的默认构造函数,其次是自己的;
4.如果父类有多个构造函数,子类默认调用父类的默认构造函数;
5.父类含有默认构造函数,子类可以没有;
6.父类没有显式的构造函数,包括默认构造函数,子类可以没有任何构造函数;
7.父类没有默认的构造函数,但有其他含有参数的构造函数,子类必需含有显示的构造函数(无论是默认无参数还是含有参数的构造函数),否则子类会报Implicit super constructor Father() is undefined for default constructor. Must define an explicit constructor
public class Father {
/*public Father(){
System.out.println("father");
}*/
public Father(int s){
System.out.println("Father.Father() "+s);
}
}
public class Child extends Father{
public Child(){
super(2);//显示调用父类含参的构造函数
System.out.println("Child");
}
/*public Child(int i){
super(i);
System.out.println("child "+i);
}*/
}
public class InheritTest {
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>Child child = new Child();
<span style="white-space:pre"> </span>//Child child2 = new Child(1);
<span style="white-space:pre"> </span>Father father = new Father(8);
<span style="white-space:pre"> </span>}
}
Father.Father() 2
Child
Father.Father() 8
8.如果父类含有默认构造函数,那么子类可以有构造函数,也可以不显示的调用;
<pre name="code" class="html">public class Father {
public Father(){
System.out.println("father");
}
public Father(int s){
System.out.println("Father.Father() "+s);
}
}
public class Child extends Father{
public Child(){
//super(2);
System.out.println("Child");
}
}
public class InheritTest {
public static void main(String[] args){
Child child = new Child();
//Child child2 = new Child(1);
Father father = new Father();
}
}
father
Child
father
9.如果父类有多个构造函数,子类也有多个构造函数
public class Father {
public Father(){
System.out.println("father");
}
public Father(int s){
System.out.println("Father "+s);
}
}
public class Child extends Father{
public Child(){
//super(2);
System.out.println("Child");
}
public Child(int i){
//super(i);
System.out.println("child "+i);
}
}
public class InheritTest {
public static void main(String[] args){
Child child = new Child();
Child child2 = new Child(1);
//Father father = new Father();
}
}
father
Child
father
child 1
子类如果有多个构造函数,父类要么没有构造函数,编译器自动产生默认构造函数,要么至少有一个缺省的构造函数可以让子类的构造函数调用。
10.子类如果想要调用父类的含参构造函数,则使用super