子类继承和调用父类的构造方法
1. 如果子类没有定义构造方法,则调用父类的无参数的构造方法,.
2. 如果子类定义了构造方法,不论是无参数还是带参数,在创建子类的对象的时候,首先执行父类无参数的构造方法,然后执行自己的构造方法。
3. 如果子类调用父类带参数的构造方法,可以通过super(参数)调用所需要的父类的构造方法,切该语句做为子类构造方法中的第一条语句。
4. 如果某个构造方法调用类中的其他的构造方法,则可以用this(参数),切该语句放在构造方法的第一条.
说白了:原则就是,先调用父亲的.(没有就默认调,有了就按有的调,反正只要有一个就可以了.)
package test;
class Father{
String s = "Run constructor method of Father";
public Father(){
System.out.println(s);
}
public Father(String str){
s= str;
System.out.println(s);
}
}
class Son extends Father{
String s= "Run constructor method of son";
public Son(){
//实际上在这里加上super(),和没加是一个样的
System.out.println(s);
}
public Son(String str){
this();//这里调用this()表示调用本类的Son(),因为Son()中有了一个super()了,所以这里不能再加了。
s = str;
System.out.println(s);
}
public Son(String str1, String str2){
super(str1+" "+str2);//因为这里已经调用了一个父类的带参数的super("---")了,所以不会再自动调用了无参数的了。
s = str1;
System.out.println(s);
}
}
public class MyClass9 {
public static void main(String[] args){
Father obfather1 = new Father();
Father obfather2 = new Father("Hello Father");
Son obson1 = new Son();
Son obson2 = new Son("hello son");
Son obson3 = new Son("hello son","hello father");
}
}
===============
结果:
Run constructor method of Father
Hello Father
Run constructor method of Father
Run constructor method of son
Run constructor method of Father
Run constructor method of son
hello son
hello son hello father
hello son
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步