OC -- 多态

多态:同一种类型 具有多种的表现形态

多态的条件:
必须存在继承关系
子类重写父类的方法
❗️父类声明的变量指向子类对象
(父类声明子类对象)

创建父类:Printer
创建子类:BlackPrinter 、ColorPrinter 、 OtherPrinter 继承Printer

Printer.h

#import 
@interface Printer : NSObject

- (void)print;
- (void)doPrint:(Printer *)printer;

@end

Printer.m

#import "Printer.h"
@implementation Printer

//使用打印机
- (void)doPrint :(Printer *)printer
{
  [printer print];
}

- (void)print
{
  NSLog(@"打印机  打印...");
}

@end

BlackPrinter.m

#import "BlackPrinter.h"
@implementation BlackPrinter
- (void)print
{
  NSLog(@"黑白打印机 打印黑白效果");
}

@end

ColorPrinter.m

#import "ColorPrinter.h"
@implementation ColorPrinter
- (void)print
{
    NSLog(@"彩色打印机");
}

@end

OtherPrinter.m

#import "OtherPrinter.h"
@implementation OtherPrinter

- (void)print
{
  NSLog(@"其他类型打印机");
}

@end

main.m

#import 
#import "BlackPrinter.h"
#import"ColorPrinter.h"
#import"Printer.h"
#import"OtherPrinter.h"

int main(int argc, const char *argv[])
{
  @autoreleasepool
  {
    enum KindOfPrinter //枚举
      {
        colorPrinter = 1,
        blackPrinter,
        otherPrinter
      };  //分号

    enum KindOfPrinter printerKind;
    NSLog(@"请选择打印机:(1彩色 2黑色 3其他)");
    scanf("%d",&printerKind);

    //父类声明变量
    Printer *printer;

    //根据类型 选择初始化方法的过程
    if(printerKind == colorPrinter)
    {
      printer = [[ColorPrinter alloc]init];
    }
    else if(printerKind == blackPrinter)
    {
      printer = [[BlackPrinter alloc]init];
    }
    else if(printerKind == otherPrinter)
    {
      printer = [[OtherPrinter alloc]init];
    }
    [printer print];
  }
  return 0;
}

你可能感兴趣的:(OC -- 多态)