zoukankan      html  css  js  c++  java
  • 08-继承和组合

    1、继承的使用场合 (继承与组合)

      (1) 当两个类拥有相同属性和方法的时候,就可以将相同的属性和方法抽取到一个父类中。

      例如:Dog 和 Cat 都拥有年龄、体重等属性,就可以把相同的属性抽取到 Animal类中;Dog 和 Cat 继承Animal,Dog Cat是子类,Aniaml是父类。

      当两个类可以用 XXX 是 xxx的形式描述的时候,它们是继承关系。

      例如:Student 是 Person 它们是继承关系 

             Dog 是 Animal 它们是继承关系

      (2) 当A类拥有B类中的部分属性和方法时,可以考虑让B类继承A类

    1>继承:

    {

      int _age;

      int _no;

    }

    B : A

    {

      int _weight;

    }

    2>组合:

    {

      int _age;

      int _no;

    }

    B

    {

      A *_a;

      int _weight;

    }

    但是有另一种情况:

     1 @interface Score : NSObject
     2 {
     3     int _cScore;
     4     int _ocScore;
     5 }
     6 @end
     7 
     8 @implementation Score
     9 @end
    10 
    11 @interface Student : NSObject
    12 {
    13     // 组合
    14     Score *_score;
    15     //    int _cScore;
    16     //    int _ocScore;
    17     int _age;
    18 }
    19 @end
    20 
    21 @implementation Student
    22 
    23 @end

          学生和成绩,二者都拥有cScore和ocScore属性,但是我们不能说学生是成绩或学生继承成绩,这不合乎逻辑;但是我们可以说学生拥有成绩,把成绩变成学生的一部分(成员属性),这种关系就是组合关系

          再例如:Dog拥有年龄和体重的属性,Person也有年龄和体重属性

    我们不能说 Dog是Person ,这样不合逻辑,这时候,我们就要换种说法:Person 拥有 Dog,这种关系便是组合关系。

      (3) 简单一点理解,判断的时候套用一下描述

      继承: xx  是 xx

      组合:xxx 拥有 xxx

    人生之路,不忘初心,勿忘始终!
  • 相关阅读:
    记录我发现的第一个关于 Google 的 Bug
    iOS 中的 Delayed Transition
    Appstore|IPA
    地图|定位
    开发者账号
    App跳转
    国际化
    短信|彩信
    闪光灯
    Cornerstone|SVN
  • 原文地址:https://www.cnblogs.com/xdl745464047/p/3999740.html
Copyright © 2011-2022 走看看