java--继承
继承
创建子类对象时,会默认创建一个他的父类对象。
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() {
}
}
静态代码块和代码块
public class Mtest {
public static void main(String[] args) {
B a=new B();
a.test();
}
}
class B {
public B() {
System.out.println("子类构造方法");
}
public void test() {
System.out.println("testB");
}
{System.out.println("代码块");}
static {
System.out.println("静态代码块");
}
}
运行结果:
静态代码块
代码块
子类构造方法
testB
静态代码块会初始化在最前面
public class Mtest {
public static void main(String[] args) {
A a=new B();
a.test();
}
}
class A {
public A() {
System.out.println("父类 构造方法");
}
public void test() {
System.out.println("testA");
}
}
class B extends A {
public B() {
System.out.println("子类 构造方法");
}
{System.out.println("代码块");}
static {
System.out.println("静态代码块");
}
public void test() {
System.out.println("testB");
}
}
运行结果:
静态代码块
父类 构造方法
代码块
子类 构造方法
testB

浙公网安备 33010602011771号