Oct 21, 2010

Abstract class and interface difference in Java

Please do not forget:
Abstract class:
---------------
1. You cannot instantiate an object of an abstract class.

2. You can implement some methods of abstract class while leaving others to be implemented by the child class that inherits the abstract class. For example:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

An abstract class is a class that is declared abstract—it may or may not include abstract methods.

If a class includes abstract methods, the class itself must be declared abstract.

3. You have to use Abstract keyword before the class keyword as well as in front of every abstract method followed by a semicolon. abstract void moveTo(double deltaX, double deltaY);


4. You can have member variables in abstract class as well as static variables.

5. Inherit only one abstract class(like any other inheritance in java) but are allowed to implement more than one interface.

6. Need not implement all the functions other than abstract methods.

IMPORTANT USAGE OF ABSTRACT CLASS:
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

Interface:
----------
1. Use the keyword interface instead of class.
a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example,

abstract class X implements Y {
// implements all but one method of Y
}

class XX extends X {
// implements the remaining method in Y
}

In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

2. No implementation of any method only method declaration.
3. Inherit i.e., more than one interface.
4. No member variables.
5. The class implementing the interface must implement all the methods of the interface.
6. All of the methods in an interface (see the Interfaces section) are implicitly abstract (as well as public), so the abstract (as well as the public) modifier is not used with interface methods (it could be—it's just not necessary).
7. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.

Reference: Abstract Class
Interface

No comments:

Down with the Dictatorship!

    "Let them hate me, so that they fear me" - Caligula 41AD