当前位置: 技术问答>java相关
抽象类和接口的讨论
来源: 互联网 发布时间:2015-08-05
本文导语: 一个抽象类,其所有方法都是public abstract,所有字段都是public static final 那么这个类和接口有什么不同? | The most important difference between abstract class and interface is what they are trying to ...
一个抽象类,其所有方法都是public abstract,所有字段都是public static final
那么这个类和接口有什么不同?
那么这个类和接口有什么不同?
|
The most important difference between abstract class and interface is what they are trying to describe.
The class is to show : what is it.
It's trying to describe the attributes of objects.
but the interface is to demonstrate : what can it do.
It's trying to describe the functions of objects.
I suggest you to look some books about UML,
they will give you more useful information about such difference.
In coding,
The interface can implements multi-inheritance.
The abstract class can have attributes.
The class is to show : what is it.
It's trying to describe the attributes of objects.
but the interface is to demonstrate : what can it do.
It's trying to describe the functions of objects.
I suggest you to look some books about UML,
they will give you more useful information about such difference.
In coding,
The interface can implements multi-inheritance.
The abstract class can have attributes.
|
一般情况下:抽象类是描述物质的。接口是描述动作的。
|
抽象类中能够实现自己的方法,可是在接口中只能定义方法,却不能实现方法!这就是他们主要的差别!
|
You’ll learn that the interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation on C++’s “multiple inheritance,” by creating a class that can be upcast to more than one base type.
Keep in mind that the core reason for interfaces is shown in the above example: to be able to upcast to more than one base type. However, a second reason for using interfaces is the same as using an abstract base class: to prevent the client programmer from making an object of this class and to establish that it is only an interface. This brings up a question: Should you use an interface or an abstract class? An interface gives you the benefits of an abstract class and the benefits of an interface, so if it’s possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes. In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change to an abstract class, or if necessary a concrete class.