Thursday, 8 August 2013

Difference between Abstarct class and Interface


An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either benull, or be bound to an object that implements the interface.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.

A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.

Abstract Class:

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Difference between  Interface and Abstract Class:

Abstract Class
A Java interface are implicitly abstract and cannot have implementations
A Java abstract class can have instance methods that implements a default behavior
Variables declared in a Java interface is by default final
An  abstract class may contain non-final variables
Members of a Java interface are public by default
A Java abstract class can have the usual flavors of class members like private, protected, etc
Java interface should be implemented using keyword “implements”
A Java abstract class should be extended using keyword “extends”
An interface can extend another Java interface only
An abstract class can extend another Java class and implement multiple Java interfaces
A Java class can implement multiple interfaces
A Java class can extend only one abstract class
Interface is absolutely abstract and cannot be instantiated
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists

Note: In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Help4J - Jar Search Engine. Easiest way to find jar and its source.

profile for Ashish Aggarwal at Stack Overflow, Q&A for professional and enthusiast programmers

No comments:

Post a Comment