abstract class and interface in C# look like much, but sometimes they get the similiar use. However, there are still much differences between them. here we go.
抽象類別和介面初看上去很象,但是還是有很多區別的。
a) Interface Grammar介面文法
[public|protected|internal|private] interface interfaceName
{
public int add(int x,int y);
//this is error! interface memeber can not be described with any characters to declare its access attribute.
//介面中任何成員和屬性不能被任何修飾符修飾來表明其訪問屬性!
int add(int x,int y);
//this is right!
int Count{get;} //interface property介面屬性
string this[int index]{get;set;}//index interface 介面索引
}
Difference:
1. in interface, all interface members can not be decorated with any other access tag,such as public,private.etc.
2. in abtract class, such case is just on the opposite.
b) abstract class Grammar 抽象類別文法
[public|protected|internal|private] abstct class className
{
public abstract int add(int x,int y);
//it's ok, but that forbidden in interface!
//在abstract class中,類成員可以有各種修飾符。如果該類成員沒有被implement,那麼該類一定要被標示為abstact方法。否則出錯!當然也可以實現該方法。如下multiply方法所示
public virtual int multiply(int x,int y)
{
return x*y;
}
}
Difference:
1.in interface, all interface memebers can not be implemented. and it's just an declaration for other class which will inherented from it and implemented all of them.
在介面中,所有介面成員都不能被實現,它只是一個申明而已,其他類繼承自該介面,並且要實現該介面中的所有成員。
2 in abstract class, its member can be implemented ,otherwise must be decorated with abstract that is the same with interface . of course, any class inherented from this must implemented all its abstract method. of course, u can also override the method that has already implemented method.
在抽象類別中,其成員可以被實現,如果不實現的話,其方法成員一定要被標標示為abstract. 同時,任何繼承於該抽象類別的類必須要實現其所有標示為abstract的方法,這點與interface相同。或者該類也可以override該抽象類別中的method. 這一點interface絕對不可能,因為interface中根本沒有實現過,何來override?