java继承时候类的运行顺序问题
2014-06-09 09:34
239 查看
子类在继承父类后,创建子类对象会首先调用父类的构造函数,先运行父类的构造函数,然后再运行子类的构造函数,例如以下所看到的:
当父类有带參数的构造函数时,子类默认是调用不带參数的构造函数,例如以下所看到的:
若想子类调用父类带參数的构造函数,须要用super()函数申明,例如以下:
class Father{ public Father(){ System.out.println("I am father"); } } public class Child extends Father{ public Child(){ System.out.println("I am child"); } public static void main(String[] args) { Father f=new Father(); Child c=new Child(); } }
当父类有带參数的构造函数时,子类默认是调用不带參数的构造函数,例如以下所看到的:
class Father{ public Father(){ System.out.println("I am father"); } public Father(String name){ System.out.println("I am father,My name is "+name); } } public class Child extends Father{ public Child(){ System.out.println("I am child"); } public static void main(String[] args) { Father f=new Father("Apache"); Child c=new Child(); } }
若想子类调用父类带參数的构造函数,须要用super()函数申明,例如以下:
class Father{ public Father(){ System.out.println("I am father"); } public Father(String name){ System.out.println("I am father,My name is "+name); } } public class Child extends Father{ public Child(){ super("Apache"); System.out.println("I am child"); } public static void main(String[] args) { Father f=new Father("Apache"); Child c=new Child(); } }
相关文章推荐
- 继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
- 继承时候类的执行顺序问题
- java中子类继承父类程序执行顺序问题
- java中子类继承父类,程序运行顺序的深入分析
- Java继承的初始化与构造函数的执行顺序问题
- 详解java中继承关系类加载顺序问题
- java中子类继承父类程序执行顺序问题
- java 子类继承父类运行顺序
- java中子类继承父类,程序运行顺序
- java中子类继承父类程序执行顺序问题
- Java继承关系中静态代码块的顺序问题
- idea运行的时候出现的问题Exception in thread “main” java.lang
- Java静态代码块、构造器、静态主方法以及继承后父类代码块的运行顺序
- java 子类继承父类运行顺序
- java继承时候关于父类中的静态方法的问题
- Java子类继承父类,构造方法的执行顺序问题
- java中子类继承父类,程序运行顺序
- Java 继承中构造方法的执行顺序问题
- java中子类继承父类代码运行顺序
- java中子类继承父类程序执行顺序问题