接口和抽象类的优点是什么? [英] What are the advantages of interfaces and abstract classes?

查看:29
本文介绍了接口和抽象类的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
类中接口的用途
接口和抽象类有什么区别?

我是一名 php 程序员.任何机构都可以解释使用接口和抽象类的好处是什么.

Hi I am a php programmer. any body can explain what is the advantage of using interface and abstract class.

推荐答案

接口的主要优点是它允许您定义要实现的协议,以使对象具有某些行为.例如,您可以有一个 Comparable 接口,其中包含一个供类实现的比较方法,并且每个实现它的类都会有一个标准化的比较方法.

The main advantage of an interface is that it allows you to define a protocol to be implemented for an object to have some behavior. For example, you could have a Comparable interface with a compare method for classes to implement, and every class that implements it would have a standardized method for comparison.

抽象类允许您为多个具体类定义一个公共基础.例如,假设您想定义代表动物的类:

Abstract classes allow you to define a common base for several concrete classes. For example, let's say you wanted to define classes representing animals:

abstract class Animal {
    abstract protected function eat();
    abstract protected function sleep();
    public function die() {
        // Do something to indicate dying
    }
}

在这种情况下,我们将 eat()sleep() 定义为抽象的,因为不同类型的动物(例如狮子、熊等)将从动物以不同的方式吃和睡.但是所有动物都以同样的方式死亡(不要强迫我这样做),因此我们可以为此定义一个通用函数.使用抽象类帮助我们 1.) 声明所有 Animal 应该具有的一些通用方法,以及 2.) 定义 Animal 的通用行为.因此,当您扩展 Animal 时,您将不必重写 die() 的代码.

In this case, we define eat() and sleep() as abstract because different types of animals (e.g. lion, bear, etc.) that will inherit from Animal eat and sleep in different ways. But all animals die the same way (don't hold me to that), so we can define a common function for that. Using an abstract class helped us 1.) declare some common methods that all Animals should have, and 2.) define common behavior for Animals. So, when you extend Animal, you won't have to rewrite the code for die().

这篇关于接口和抽象类的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆