技术开发 频道

Perl的面向对象编程

  十一、子类方法的重载

  继承的好处在于可以获得基类输出的方法的功能,而有时需要对基类的方法重载以获得更具体或不同的功能。下面在Bean.pm类中加入方法printType(),代码如下:

  sub printType {   my $class = shift @_;   print "The type of Bean is $class->{"Bean"} n";   }

  然后更新其@EXPORT数组来输出:

  @EXPORT = qw ( setBeanType , printType );

  现在来调用函数printType(),有三种调用方法:

  $cup->Coffee::printType();

  $cup->printType();

  $cup->Bean::printType();

  输出分别如下:

  The type of Bean is Mixed

  The type of Bean is Mixed

  The type of Bean is Mixed

  为什么都一样呢?因为在子类中没有定义函数printType(),所以实际均调用了基类中的方法。如果想使子类有其自己的printType()函数,必须在Coffee.pm类中加以定义:

  #   # This routine prints the type of $class->{"Coffee"}   #   sub printType {   my $class = shift @_;   print "The type of Coffee is $class->{"Coffee"} n";   }

  然后更新其@EXPORT数组:

  @EXPORT = qw(setImports, declareMain, closeMain, printType);

  现在输出结果变成了:

  The type of Coffee is Instant

  The type of Coffee is Instant

  The type of Bean is Mixed

  现在只有当给定了Bean::时才调用基类的方法,否则直接调用子类的方法。

  那么如果不知道基类名该如何调用基类方法呢?方法是使用伪类保留字SUPER::。在类方法内使用语法如:$this->SUPER::function(...argument list...); ,它将从@ISA列表中寻找。刚才的语句用SUPER::替换Bean::可以写为$cup->SUPER::printType(); ,其结果输出相同,为:

  The type of Bean is Mixed

 

0
相关文章