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

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

问题描述


可能重复:

课程中接口的目的

接口和抽象类有什么区别?

您好,我是一名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()定义为摘要因为不同类型的动物(如狮子,熊等)将继承自 Animal 以不同方式进食和睡眠。但是所有的动物都以同样的方式死亡(不要抱我这样),所以我们可以为此定义一个共同的功能。使用抽象类帮助我们1.)声明一些所有 Animal s应该具有的常用方法,以及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天全站免登陆