/**
* 父类Parent
*
*/
public class Parent {
public String strName;
public int intAge;
/**
* 无参构造函数
*
*/
public Parent() {
System.err.println("Parent无参构造函数");
}
/**
* 有参构造函数
* @param strName
* @param intAge
*/
public Parent(String strName , int intAge) {
strName = this.strName;
intAge = this.intAge;
System.err.println("Paren有参构造函数");
}
}
/**
* 子类Parent
*
*/
public class Child extends Parent {
public String strName;
public int intAge;
/**
* 无参构造函数
*/
public Child(){
System.err.println("Child无参构造函数");
};
public Child(String strName , int intAge) {
strName = this.strName;
intAge = this.intAge;
System.err.println("Child有参构造函数");
}
}
/**
*
* 测试类别
*/
public class ExtendTest {
/**
* @param args
*/
public static void main(String[] args) {
Parent parent = new Parent(); (1)
Child child = new Child(); (2)
Parent parentTest = new Child(); (3)
}
}
(1)结果
============
Parent无参构造函数
============
(2)结果
============
PaParent无参构造函数
Child无参构造函数
============
(3)结果
============
PaParent无参构造函数
Child无参构造函数
============
总结
1).调用子类别的构造方法,会先行调用父类别的构造方法.
2).如果有自定义的构造方法,编译器就不会提供无参构造方法.否则,编译器会提供无参构造方法.
3).如果Parent中没有重写无参构造方法,编译会通过.因为子类在寻找父类的构造方法的时候,发现只有带参数的构造方法.而没有无参构造方法.
4).同样如果想将Parent中无参构造方法的访问级别设为private,同样会有3)中的问题.
5).子类想调用父类的构造方法,用super();
* 父类Parent
*
*/
public class Parent {
public String strName;
public int intAge;
/**
* 无参构造函数
*
*/
public Parent() {
System.err.println("Parent无参构造函数");
}
/**
* 有参构造函数
* @param strName
* @param intAge
*/
public Parent(String strName , int intAge) {
strName = this.strName;
intAge = this.intAge;
System.err.println("Paren有参构造函数");
}
}
/**
* 子类Parent
*
*/
public class Child extends Parent {
public String strName;
public int intAge;
/**
* 无参构造函数
*/
public Child(){
System.err.println("Child无参构造函数");
};
public Child(String strName , int intAge) {
strName = this.strName;
intAge = this.intAge;
System.err.println("Child有参构造函数");
}
}
/**
*
* 测试类别
*/
public class ExtendTest {
/**
* @param args
*/
public static void main(String[] args) {
Parent parent = new Parent(); (1)
Child child = new Child(); (2)
Parent parentTest = new Child(); (3)
}
}
(1)结果
============
Parent无参构造函数
============
(2)结果
============
PaParent无参构造函数
Child无参构造函数
============
(3)结果
============
PaParent无参构造函数
Child无参构造函数
============
总结
1).调用子类别的构造方法,会先行调用父类别的构造方法.
2).如果有自定义的构造方法,编译器就不会提供无参构造方法.否则,编译器会提供无参构造方法.
3).如果Parent中没有重写无参构造方法,编译会通过.因为子类在寻找父类的构造方法的时候,发现只有带参数的构造方法.而没有无参构造方法.
4).同样如果想将Parent中无参构造方法的访问级别设为private,同样会有3)中的问题.
5).子类想调用父类的构造方法,用super();