抽象类和接口的比较

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
抽象类,是没有实现“完全”的类,里面包含了一个或者多个抽象方法,这些抽象方法需要子类实现。所以抽象类一定是要被继承的,不能实例化。

An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.

接口“类似于”一个完全抽象的class,所有方法都没有实现。但是接口本身并不是类,这里只是“类似于”。

An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can’t do anything. It’s just a pattern.

For example (pseudo code):

// I say all motor vehicles should look like this:
interface MotorVehicle
{
    void run();

    int getFuel();
}

// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{

    int fuel;

    void run()
    {
        print("Wrroooooooom");
    }


    int getFuel()
    {
        return this.fuel;
    }
}

Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there isn’t any expensive look-up to do. It’s great when it matters, such as in embedded devices.

Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It’s more about a guy saying, “these classes should look like that, and they have that in common, so fill in the blanks!”.

// I say all motor vehicles should look like this:
abstract class MotorVehicle
{

    int fuel;

    // They ALL have fuel, so why not let others implement this?
    // Let's make it for everybody.
    int getFuel()
    {
         return this.fuel;
    }

    // That can be very different, force them to provide their
    // implementation.
    abstract void run();
}

// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
    void run()
    {
        print("Wrroooooooom");
    }
}

所以,
抽象类更像是对一系列类的抽象,这些类的共性(相同点)提取出来在抽象类中实现,而不同点在抽象类中不实现,等待具体的子类去实现,这样是不是省了不少代码^_^。
而接口更像是为了面向接口编程而实现的,一个组织(类似于sun)提出了一个标准,这些标准其实可以看做一系列接口,sun并不去具体实现这些“功能”,而第三方负责实现这个标准,例如apache tomcat,将“标准”和“实现”分开。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值