码迷,mamicode.com
首页 > 编程语言 > 详细

java继承时候类的运行顺序问题

时间:2014-06-09 19:22:33      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

子类在继承父类后,创建子类对象会首先调用父类的构造函数,先运行父类的构造函数,然后再运行子类的构造函数,例如以下所看到的:


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();
	}
}

bubuko.com,布布扣

当父类有带參数的构造函数时,子类默认是调用不带參数的构造函数,例如以下所看到的:


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();
	}
}

bubuko.com,布布扣

若想子类调用父类带參数的构造函数,须要用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();
	}
}

bubuko.com,布布扣

java继承时候类的运行顺序问题,布布扣,bubuko.com

java继承时候类的运行顺序问题

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/hrhguanli/p/3777254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!