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,将“标准”和“实现”分开。