public class Supertest {
public Supertest() {
System.out.println("父类构造方法");
}
}
public class Child extends Supertest {
}
public class Jmain {
public static void main(String[] args) {
Child c=new Child();
}
}
运行结果:
>>父类构造方法
public class Supertest {
private int a;
public Supertest(int a) {
System.out.println("父级构造函数");
this.a = a;
}
}
public class Child extends Supertest {
public Child() {
}
}
Implicit super constructor Supertest() is undefined. Must explicitly invoke another constructor
这里会报错:未定义父级Supertest()的隐式构造函数。必须显示地调用另一个构造函数。
一般不写的情况下会默认有一个隐式构造函数(无参的构造函数),但上面父级里写了一个有参的构造函数,这样就覆盖了隐式的。
而子级定义的构造函数里的隐藏的super( );会去默认调用父级的隐式构造函数,这时间却找不到父级的隐式构造函数了。
解决方法有两个;
1.在父级里把隐式构造函数写出来
public class Supertest {
private int a;
//隐式构造函数
public Supertest() {
}
public Supertest(int a) {
System.out.println("父级构造函数");
this.a = a;
}
}
2.在子级的有参构造函数里用super(a );去显式的调用父级里的有参构造函数
public class Child extends Supertest {
public Child(int a) {
super(a);
}
}
public class Supertest {
public void test() {
System.out.println("this is test");
}
}
public class Child extends Supertest {
public void hello() {
System.out.println("this is hello");
}
}
public class Jmain {
public static void main(String[] args) {
Child a=new Child();
a.hello();
a.test();
}
}
运行结果:
>>
this is hello
this is test
public class Jmain {
public static void main(String[] args) {
Supertest b=new Child();
b.test();
b.hello();
}
}
这里会运行失败,原因是无法编译
原因:b.hello();这个是错误的,因为父级创建的一个变量是指向了child()对象的地址空间;但是无法调用他的方法。
解决办法:
可以在父级类里写一个空的hello方法;
public class Supertest {
public void test() {
System.out.println("this is test");
}
public void hello() {
}
}
原文:https://www.cnblogs.com/lyhtzjr/p/12163615.html