问题代码举例:
package t1;
class Base
{
int x;
public Base(int i)
{
x =i;
System.out.println("Base() method");
}
}
public class Abs extends Base
{
int y;
public Abs()
{
y = 1;
System.out.println("Abs() method");
}
public static void main(String argv[])
{
Abs a = new Abs();
System.out.println(a.x);
System.out.println(a.y);
}
}
问题描述:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Base() is undefined. Must explicitly invoke another constructor
at t1.Abs.<init>(Abs.java:17)
at t1.Abs.main(Abs.java:24)
问题原因分析:
当子类继承父类,构造子类对象时,子类的构造方法会默认的调用父类的构造方法。虽然父类重写了构造方法,变成有参构造方法,但是这样有参构造方法就会覆盖无参的构造方法,而且不管子类的构造函数是的形式如何,都会默认调用父类的默认的无参的构造函数。
解决方法:
1.去掉有参构造方法。
2.再写一个无参构造方法。
3.指定子类构造方法要调用的父类的构造方法。