Abstract Classes vs. Interfaces
Abstract classes and interfaces have a lot in common. For example, both can declare methods that all the deriving classes should define. They are also similar in the respect that you can create instances neither of an abstract class nor of an interface.
Abstract Classes and Interfaces: Syntactical Differences
- An abstract class can provide default implementation of methods but you cannot define methods in an interface; you can only declare them.
- An abstract class can have static and non-static fields but You cannot have any fields (instance variables) in an interface.
- An abstract class can have both static and non-static constants but Interfaces can have only static constants. If you declare a field, it must be initialized. All fields are implicitly considered to be declared as public static and final.
- You can define a constructor in an abstract class but you cannot declare/define a constructor in an
- interface.
- You can have private and protected members in an abstract class but You cannot have any private or protected members in an interface; all members are public by default.
- A class can inherit only one class but A class can implement any number of interfaces.
- An abstract base class provides a protocol; in addition, it serves as a base class in an is-a relationship. but An interface provides only a protocol. It specifies functionality that must be implemented by the classes implementing it.
- An abstract class can provide a default implementation of a method. So, derived class(es) can just use that definition and need not define that method. but An interface can only declare a method. Allclasses implementing the interface must define that method.
- It is possible to make changes to the implementation of an abstract class. For example, you can add a method with default implementation and the existing derived classes will not break. but If there are already many classes implementing an interface, you cannot easily change that interface. For example, if you declare a new method, all the classes implementing that interface will stop compiling since they do not define that method.
Choosing Between an Abstract Class and an Interface
When should you choose abstract classes, and when should you choose interfaces?
- If you are identifying a base class that abstracts common functionality from a set of related classes, you should use an abstract class. If you are providing common method(s) or protocol(s) that can be implemented even by unrelated classes, this is best done with an interface.
- If you want to capture the similarities among the classes (even unrelated) without forcing a class relationship, you should use interfaces. On the other hand, if there exists an is-a relationship between the classes and the new entity, you should declare the new entity as an abstract class.
No comments:
Post a Comment