一个纯粹的抽象类和接口的区别 [英] Difference between a Pure Abstract class and an Interface

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

问题描述

我有一个同事,谁坚持认为,在语言如Java和C#从未有任何理由使用纯抽象基类,因为它只是意味着你无法绕开缺乏多重继承的讨论

I was having a discussion with a coworker, who insisted that in Languages such as Java and C# there is never any reason to use a Pure Abstract base class, as it simply means you are unable to get around the lack of multiple inheritance.

我觉得他是错了这一点,因为我一直认为,如果一件事情是一个名词那么它就是一个对象,如果它是一个动词那么它是一个接口。

I feel that he is wrong about this, as I've always thought that if a thing is a noun then it is an object, and if it is a verb then it is an interface.

例如,如果我想定义类型禽流,在这里我想强制执行该方法没有实现它,那么我会做一个纯粹的抽象类。

For example, if I wanted to define type Bird, where I wanted to enforce the method fly without implementing it, then I would make that a pure abstract class.

如果我想定义一类苍蝇,我会使其与方法的界面。

If I wanted to define a type Flies, I would make it an interface with the method fly.

禽流可能实施苍蝇

我错了

编辑:

唯一坚实的论据,我可以给支持我的观点。的观点是,在未来的某个时候,设计可能需要改变,这样的鸟可以吃了。如果所有的鸟吃一样那么这将需要添加到禽流,使其成为非纯粹的抽象。

The only solid argument I can give to support my point of view is that at some point in the future the design might need to change so that birds can eat. If all birds eat the same then this would need to be added to Bird, making it non pure abstract.

如果禽流一直接口这个变化,简直是一场噩梦,因为我不知道是否东西继承从一些其他的基类也实现了我的禽流接口,所以我不能只是重构自己的问题了。

If Bird had been an interface this change would simply be a nightmare, since I cannot know whether things that inherit from some other base class also implement my Bird interface, so I can't just refactor my problems away.

推荐答案

除了你的第一个编辑即未来的一些需求。一个可能的用例可以宣布一个常数,在抽象类初始化它

Apart from your first edit i.e some future requirement. One possible use-case could declaring a constant and initializing it in the abstract class.

import java.util.ArrayList;
import java.util.List;


public abstract class AbstractPure implements ISomeInterface {
    public static final List<String> days = new ArrayList<String>();
    static{
        days.add("Monday");
        days.add("Tuesday");
        days.add("Wednesday");      
        days.add("Thursday");   
        days.add("Friday"); 
        days.add("Saturday");   
        days.add("Sunday"); 
    }
}

这篇关于一个纯粹的抽象类和接口的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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