Abstract classes are similar to interfaces, but they have different ideas. An interface is a member of a public class, while an abstract class is a member of an abstract class to require subclass inheritance and implementation.
Abstract class: abstract class is an abstraction of commonalities.
- Unlike normal classes, abstract classes must be modified using abstract.
- If a class contains abstract methods, the class must be abstracted (declared as an abstract class and not implemented ).
- The subclass that inherits the abstract class must override the abstract method of the parent class.
- Abstract classes cannot be instantiated.
- Abstract classes can be used for polymorphism.
- It can contain abstract methods and non-abstract methods.
- Members can use static, abstract, override, and virtual modifiers.
Define abstract classes and abstract methods:
abstract class CashSuper{ public abstract double acceptCash(double money);}
Abstract methods using abstract classes:
class CashNormal : CashSuper{ public override double acceptCash(double money) { return money; }}
Interface: an interface is an abstraction of behavior.
- Any non-Abstract type that implements an interface must implement all the members of the interface.
- The interface cannot be instantiated.
- Interfaces can contain events, indexers, methods, and attributes.
- Classes and structures can inherit multiple interfaces.
- The interface itself can be inherited from multiple interfaces.
- Methods can only be abstract methods.
- All members are public static final and cannot use static, abstract, override, or virtual modifiers.
Example:
interface MyInterface { string ID { set; get; } string Name { set; get; } void ShowInfo(); }
Differences between interfaces and abstract classes