(三)构造方法

1.构造方法必须与定义它的类有完全相同的名字,构造方法没有返回值,也不允许void
2.类可以不声明构造方法,这时类中隐含声明了一个方法体为空的无参构造方法。但当类有明确声明构造方法时,它就不会自动生成
3.构造方法的调用:子类必须要先调用父类够高方法才能继承父类的属性和方法。如果子类的构造方法中没有显式地调用父类的构造方法,则系统默认调用父类无参的构造方法—这句话存在2种情况
①父类和子类都没有显式定义构造方法或只定义了无参的构造方法,这种情况下,Java会顺着集成结构往上一直找到Object,然后从Object开始往下以此执行构造函数。

public class father {

	//构造方法必须与定义它的类有完全相同的名字,构造方法没有返回值,也不允许void
	public  father(){
		System.out.println("father construct ...");
	}
	public static void main(String[] args) {
		
	}
}

public class child extends father{

	public child(){
	//这里隐藏了super()
		System.out.println("child construct ...");
	}
	
}


public class grandSon extends child {

	public grandSon(){
	   //其实这里隐藏了super() 
		System.out.println("grandSon construct ...");
	}
	public static void main(String[] args) {
		grandSon ch=new grandSon();  //构造函数并不能被继承
		
	}
}

执行结果:
father construct ...
child construct ...
grandSon construct ...

②父类只定义有参构造方法,那么无论子类如何定义,编译都会报错,因为父类缺少无参构造方法,此时子类的构造函数中必须显式地调用父类的构造函数这也是为什么父类一般要写个无参的构造方法的原因。当父类有无参的构造方法时,就会默认在子类的构造函数第一行默认执行super()

public class father {

	private String name;
	
	public  father(String name){  //父类只有含参的构造函数
		System.out.println("father construct ...");
		this.name=name;
	}
}

public class child extends father{

	private int age;
	public child(int age){
		super("fatherName");  //必须显式调用,因为没有隐式的没有参数的构造函数,根据2
		System.out.println("child construct ...");
		
	}
}

执行结果:father construct ...
         child construct ...

4.构造函数不能被继承,因此不能被覆盖,但是构造函数能够被重载,可以使用不同的参数个数或参数类型来定义多个构造函数

5.构造函数总是伴随着new操作一起调用,且不能由程序的编写者调用,只能系统调用。构造函数在对象实例化时被自动调用,只运行一次;而普通函数可以被对象调用多次,用到手动调用

6.构造函数的作用:完成对象的初始化工作

posted @ 2019-01-26 15:02  测试开发分享站  阅读(132)  评论(0编辑  收藏  举报