侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Java中继承图文详解

Java  /  管理员 发布于 8年前   361

java继承与合成基本概念

继承:可以基于已经存在的类构造一个新类。继承已经存在的类就可以复用这些类的方法和域。在此基础上,可以添加新的方法和域,从而扩充了类的功能。

合成:在新类里创建原有的对象称为合成。这种方式可以重复利用现有的代码而不更改它的形式。

相关视频教程推荐:java视频教程

1.继承的语法

关键字extends表明新类派生于一个已经存在的类。已存在的类称为父类或基类,新类称为子类或派生类。例如:

class Student extends Person {}

类Student继承了Person,Person类称为父类或基类,Student类称为子类或派生类。

2.合成的语法

合成比较简单,就是在一个类中创建一个已经存在的类。

class Student {    Dog dog;}

上溯造型

1.基本概念

继承的作用在于代码的复用。由于继承意味着父类的所有方法亦可在子类中使用,所以发给父类的消息亦可发给衍生类。如果Person类中有一个eat方法,那么Student类中也会有这个方法,这意味着Student对象也是Person的一种类型。

class Person {    public void eat() {        System.out.println("eat");    }    static void show(Person p) {        p.eat();    }}public class Student extends Person{    public static void main(String[] args) {        Student s = new Student();        Person.show(s);     // ①    }}

【运行结果】:
eat

在Person中定义的show方法是用来接收Person句柄的,但是在①处接收的却是Student对象的引用。这是因为Student对象也是Person对象。在show方法中,传入的句柄(对象的引用)可以是Person对象以及Person的衍生类对象。这种将Student句柄转换成Person句柄的行为成为上溯造型。

2.为什么要上溯造型

为什么在调用eat是要有意忽略调用它的对象类型呢?如果让show方法简单地获取Student句柄似乎更加直观易懂,但是那样会使衍生自Person类的每一个新类都要实现专属自己的show方法:

class Value {    private int count = 1;    private Value(int count) {        this.count = count;    }    public static final Valuev1 = new Value(1),v2 = new Value(2),v3 = new Value(3);}class Person {    public void eat(Value v) {        System.out.println("Person.eat()");    }}class Teacher extends Person {    public void eat(Value v) {        System.out.println("Teacher.eat()");    }}class Student extends Person {    public void eat(Value v) {        System.out.println("Student.eat()");    }}public class UpcastingDemo {    public static void show(Student s) {        s.eat(Value.v1);    }    public static void show(Teacher t) {        t.eat(Value.v1);    }    public static void show(Person p) {        p.eat(Value.v1);    }    public static void main(String[] args) {        Student s = new Student();        Teacher t = new Teacher();        Person p = new Person();        show(s);        show(t);        show(p);    }}

这种做法一个很明显的缺陷就是必须为每一个Person类的衍生类定义与之紧密相关的方法,产生了很多重复的代码。另一方面,对于如果忘记了方法的重载也不会报错。上例中的三个show方法完全可以合并为一个:

public static void show(Person p) {     p.eat(Value.v1);}

动态绑定

当执行show(s)时,输出结果是Student.eat(),这确实是希望得到的结果,但是似乎没有按照我们希望的形式来执行,再来看一下show方法:

public static void show(Person p) {     p.eat(Value.v1);}

它接收的是Person句柄,当执行show(s)时,它是如何知道Person句柄指向的是一个Student对象而不是Teacher对象呢?编译器是无从得知的,这涉及到接下来要说明的绑定问题。

1.方法调用的绑定

将一个方法同一个方法主体连接在一起就称为绑定(Binding)。若在运行运行前执行绑定,就称为“早期绑定”。上面的例子中,在只有一个Person句柄的情况下,编译器不知道具体调用哪个方法。Java实现了一种方法调用机制,可在运行期间判断对象的类型,然后调用相应的方法,这种在运行期间进行,以对象的类型为基础的绑定称为动态绑定。除非一个方法被声明为final,Java中的所有方法都是动态绑定的。

用一张图表示上溯造型的继承关系:

1.jpg

用代码概括为:

Shape s = new Shape();

按照继承关系,将创建的Circle对象句柄赋给一个Shape是合法的,因为Circle属于Shape的一种。

当调用其中一个基础类方法时:

Shape s = new Shape();

此时,调用的是Circle.draw(),这是由于动态绑定的原因。

class Person {    void eat() {}    void speak() {}}class Boy extends Person {    void eat() {        System.out.println("Boy.eat()");    }    void speak() {        System.out.println("Boy.speak()");    }}class Girl extends Person {    void eat() {        System.out.println("Girl.eat()");    }    void speak() {        System.out.println("Girl.speak()");    }}public class Persons {    public static Person randPerson() {        switch ((int)(Math.random() * 2)) {        default:        case 0:return new Boy();        case 1:return new Girl();        }    }    public static void main(String[] args) {        Person[] p = new Person[4];        for (int i = 0; i < p.length; i++) {p[i] = randPerson();    // 随机生成Boy或Girl        }        for (int i = 0; i < p.length; i++) {p[i].eat();        }    }}

对所有从Person衍生出来的类,Person建立了一个通用接口,所有衍生的类都有eat和speak两种行为。衍生类覆盖了这些定义,重新定义了这两种行为。

在主类中,randPerson随机选择Person对象的句柄。**上诉造型是在return语句里发生的。**return语句取得一个Boy或Girl的句柄并将其作为Person类型返回,此时并不知道具体是什么类型,只知道是Person对象句柄。

在main方法中调用randPerson方法为数组填入Person对象,但不知具体情况。当调用数组每个元素的eat方法时,动态绑定的作用就是执行对象的重新定义了的方法。

然而,动态绑定是有前提的,绑定的方法必须存在于基类中,否则无法编译通过。

class Person {    void eat() {        System.out.println("Person.eat()");    }}class Boy extends Person {    void eat() {        System.out.println("Boy.eat()");    }    void speak() {        System.out.println("Boy.speak()");    }}public class Persons {    public static void main(String[] args) {        Person p = new Boy();        p.eat();        p.speak();  // The method speak() is undefined for the type Person    }}

如果子类中没有定义覆盖方法,则会调用父类中的方法:

class Person {    void eat() {        System.out.println("Person.eat()");    }}class Boy extends Person {}public class Persons {    public static void main(String[] args) {        Person p = new Boy();        p.eat();    }}

【运行结果】:
Person.eat()

2.静态方法的绑定

将上面的方法都加上static关键字,变成静态方法:

class Person {    static void eat() {        System.out.println("Person.eat()");    }    static void speak() {        System.out.println("Person.speak()");    }}class Boy extends Person {    static void eat() {        System.out.println("Boy.eat()");    }    static void speak() {        System.out.println("Boy.speak()");    }}class Girl extends Person {    static void eat() {        System.out.println("Girl.eat()");    }    static void speak() {        System.out.println("Girl.speak()");    }}public class Persons {    public static Person randPerson() {        switch ((int)(Math.random() * 2)) {        default:        case 0:return new Boy();        case 1:return new Girl();        }    }    public static void main(String[] args) {        Person[] p = new Person[4];        for (int i = 0; i < p.length; i++) {p[i] = randPerson();    // 随机生成Boy或Girl        }        for (int i = 0; i < p.length; i++) {p[i].eat();        }    }}

【运行结果】:

Person.eat() Person.eat() Person.eat() Person.eat()

观察结果,对于静态方法而言,不管父类引用指向的什么子类对象,调用的都是父类的方法。

更多java相关文章请关注java基础教程栏目。

以上就是Java中继承图文详解的详细内容,更多请关注其它相关文章!


  • 上一条:
    java中线程的完整生命周期有哪几种状态
    下一条:
    java中关于对象的详细介绍
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在java中实现的脱敏工具类代码示例分享(0个评论)
    • zookeeper安装流程步骤(0个评论)
    • 在java中你背的“八股文”可能已经过时了(2个评论)
    • 在php8.0+版本中使用属性来增加值代码示例(3个评论)
    • java 正则表达式基础,实例学习资料收集大全 原创(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-11
    • 2018-03
    • 2020-03
    • 2023-05
    • 2023-11
    • 2024-01
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客