zoukankan      html  css  js  c++  java
  • 继承的实现

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

          从英文字面意思理解,extends的意思是“扩展”。子类是父类的扩展。现实世界中的继承无处不在。比如:

     图5-1 现实世界中的继承.png

    图5-1 现实世界中的继承

          上图中,哺乳动物继承了动物。意味着,动物的特性,哺乳动物都有;在我们编程中,如果新定义一个Student类,发现已经有Person类包含了我们需要的属性和方法,那么Student类只需要继承Person类即可拥有Person类的属性和方法。

    【示例】使用extends实现继承

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    public class Test{
        public static void main(String[] args) {
            Student s = new Student("高淇",172,"Java");
            s.rest();
            s.study();
        }
    }
    class Person {
        String name;
        int height;
        public void rest(){
            System.out.println("休息一会!");
        }  
    }
    class Student extends Person {
        String major; //专业
        public void study(){
            System.out.println("在尚学堂,学习Java");
        }  
        public Student(String name,int height,String major) {
            //天然拥有父类的属性
            this.name = name;
            this.height = height;
            this.major = major;
        }
    }

          

    图5-2 示例5-1运行效果图.png

  • 相关阅读:
    Codeforces 1485C Floor and Mod (枚举)
    CodeForces 1195D Submarine in the Rybinsk Sea (算贡献)
    CodeForces 1195C Basketball Exercise (线性DP)
    2021年初寒假训练第24场 B. 庆功会(搜索)
    任务分配(dp)
    开发工具的异常现象
    Telink MESH SDK 如何使用PWM
    Telink BLE MESH PWM波的小结
    [LeetCode] 1586. Binary Search Tree Iterator II
    [LeetCode] 1288. Remove Covered Intervals
  • 原文地址:https://www.cnblogs.com/huaxiansheng/p/15310923.html
Copyright © 2011-2022 走看看