首页 > 编程语言 > 详细

java--继承

时间:2020-01-07 21:37:16      阅读:94      评论:0      收藏:0      [点我收藏+]

继承


创建子类对象时,会默认创建一个他的父类对象。
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() {
        
    }
}

java--继承

原文:https://www.cnblogs.com/lyhtzjr/p/12163615.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!