Java——继承

继承是面向对象编程的三大特征之一,它让我们更加容易实现对已有类的扩展、更加容易实现对现实世界的建模。

继承有两个主要作用:

  1. 代码复用,更加容易实现类的扩展
  2. 方便建模

继承的实现

继承让我们更加容易实现对类的扩展。比如我们定义了人类,再定义Boy类就只需要扩展人类即可。实现了代码的重用,不用再重新发明轮子(don't reinvent wheels)

从英文字面意思理解,extends的意思是"扩展"。子类是父类的扩展。现实生活中的继承关系无处不在。比如在我们的编程中,如果新定义一个Student类,发现已经有Person类包含了我们需要的属性和方法,那么Student类只需要继承Person类即可拥有Person类的属性和方法。

使用extends实现继承的示例代码

java 复制代码
package com.bjsxt.test2;

public class Eeeeextends {
    public static void main(String[]args){
        Student s=new student("Anny",188,"java");
        s.rest();
        s.study();
    }
}
class Person{
    String name;
    int height;
    public void
        rest(){System.out.println("休息一会儿!");
        }

}
class Students extends Person{
    String major;
    public void study(){
        public Students(String name,int height,String major){
            this.name=name;
            this.height=height;
            this.major=major;
        }
    }
}
相关推荐
平常心的技术小牛3 小时前
Qt-快速上手-QMenuBar
开发语言·qt
青 春 记 忆3 小时前
零基础入门Python11|Git实战:为任务管理器建立版本历史
开发语言·git·vscode·python·python3.11
2601_963870204 小时前
【计算机毕业设计】基于Spring Boot的专科医院医疗管理系统
java·spring boot·课程设计
Bingo_BIG4 小时前
Java Spring 批量修改,实体、接口、方法的定义
java·spring
画中有画5 小时前
软件架构中质量属性(性能、安全、可扩展性)的权衡设计
java·运维·安全
Shaoxi Zhang5 小时前
JAVA学习笔记035——对象和JSON格式
java·笔记·学习
赵丙双5 小时前
CountDownLatch 源码分析
java·aqs·countdownlatch
余额瞒着我当琳5 小时前
C++--深拷贝三件套 + swap + 写时拷贝 + vector 扩容 + reserve
java·开发语言·c++
thefool1122665 小时前
翻转二叉树
java
坐吃山猪6 小时前
WebClient内存配置解析
开发语言·springboot·webflux