Hi,
What's the difference between an interface and an abstract class in Java?
Hi,
What's the difference between an interface and an abstract class in Java?
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
An Abstract Class can contain default Implementation, where as an Interface should not contain any implementation at all. An Interface should contain only definitions but no implementation. where as an abstract class can contain abstract and non-abstract methods. When a class inherits from an abstract, the derived class must implement all the abstract methods declared in the base class. an abstract class can inherit from another non-abstract class.
1. Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
2. Variables declared in a Java interface is by default final. A Java abstract class may contain non-final variables.
3. Memebers of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one abstract class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
Neither Interface or Abstract classes can be instantiated. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Use interface as much as possible and only use an abstract class in the case where you want to provide some (but not all, of course) implementation. In practice, you want to prefer using, passing and returning interfaces, not abstract class references. I think even in the case where you have an abstract class to share some implementation, you still want to have an interface represent what will be used by the client (for an example look at the new Collections -- you often pass around Collection, List, Set or Map references, but not a AbstractList, AbstractSet or AbstractMap, references)
Bookmarks