C#中的抽象类VS接口

时间:2013-09-12 14:49:02

标签: c# interface

有人可以解释何时使用抽象类和接口与实际例子......

1 个答案:

答案 0 :(得分:2)

考虑一个所有汽车will have 4 tyres and other features can be different的场景。 在这种情况下,Car has to have 4 tyres.的任何子类都是abstract class will be useddefault implementaion for tyres will be provided的情况。

public abstract class Car{

public abstract String getCarName();

public final int getNoOfTyres(){
   return 4;
} 

}

考虑Cars可以any number of tyresother features can also be different的情况。在这种情况下,将创建interface

public interface Car{

public abstract String getCarName();
public abstract int getNoOfTyres();
}

Source