父类如果不写无参构造方法,子类会报错

1. 如果在类中你提供了其他有参的构造器,则编译器不会提供默认的无参构造器。

 

class Animal {
	Animal(String name) { }
	public static void main(String[] args){
		Animal a = new Animal();
	}
}

 

 

该段代码编译不会通过,报错信息如下:

 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
<span style="white-space:pre">	</span>The constructor Animal() is undefined

 

 

2. 如果在类中你没有提供任何构造器,则编译器会提供一个默认的无参构造器。

 

class Animal {
	public static void main(String[] args){
		Animal a = new Animal();
	}
}


该段代码则会顺利编译通过。

 

 

3. 如果你提供了一个构造器,你无须手动添加super()到你的构造器,编译器会默认添加。

 

class Animal {
	Animal (){
		System.out.println("----Animal无参构造器-----");
	}
}
class Horse extends Animal {
	Horse() {
//		super(); //此行代码有与没有都是一样的
		System.out.println("----Horse无参构造器-----");
	}
	Horse(int a) {
//		super(); //此行代码有与没有都是一样的
		System.out.println("----Horse有参构造器-----");
	}
	public static void main(String[] args){
		Horse a = new Horse();
		Horse b = new Horse(3);
	}
}


打印信息如下:

 

 

----Animal无参构造器-----
----Horse无参构造器-----
----Animal无参构造器-----
----Horse有参构造器-----


4. 如果父类未提供无参构造器,子类会报错:

 

 

class Animal {
	Animal (int a){
		System.out.println("----Animal有参构造器-----");
	}
}
class Horse extends Animal {
	Horse() {
		System.out.println("----Horse无参构造器-----");
	}
	public static void main(String[] args){
		Horse a = new Horse();
	}
}


该代码不会编译通过,报错如下:

 

 

Implicit super constructor Animal() is undefined. Must explicitly invoke another constructor


5. 如果构造器中添加了this引用该类的其他构造器,或者添加了super()调用父类构造器,this和super必须在构造器第一行,this引用其他构造器和super()语句不会同时出现

 

 

class Animal {
	Animal (){
		System.out.println("----Animal无参构造器-----");
	}
}
class Horse extends Animal {
	String name;
	Horse() {
		System.out.println("----Horse无参构造器-----");
		this("马");  //提示错误,
	}
	Horse(String name){
		this.name = name;
	}
}


具体错误提示为:Constructor call must be the first statement in a constructor

 

 

6. 如果构造器中添加了this引用该类的其他构造器,或者添加了super()调用父类构造器,如果this和super中有参数,则只能是静态的方法和静态变量或常量

 

class Animal {
	Animal (){
		System.out.println("----Animal无参构造器-----");
	}
}
class Horse extends Animal {
	String name;
	Horse() {
		this(getRondomName());<span style="font-family:Arial, Helvetica, sans-serif;"> //代码段A</span>
		System.out.println("----Horse无参构造器-----");
	}
	Horse(String name){
		System.out.println("----Horse有参构造器-----"); //代码段B
		this.name = name;
	}
	static String getRondomName(){
		int x = (int) (Math.random() * 5);
		String name = new String[] {"马", "猪", "牛", "羊","猫"}[x];
		return name;
	}
	public static void main(String[] args){
		Horse a = new Horse();
	}
}


打印结果如下:

 

 

----Animal无参构造器-----
----Horse有参构造器-----
----Horse无参构造器-----


如果调用了this引用其他构造器,那么super()将不会在该构造器中调用,所以super()将在代码段B前面一行被调用,而不是在代码段A前面一行。

 

如果把getRondomName方法前的static去掉,则会提示错误:Cannot refer to an instance method while explicitly invoking a constructor

posted @ 2017-09-05 17:38  半路和尚会念经  阅读(1866)  评论(0编辑  收藏  举报