Wednesday, March 18, 2009

Situations for using Interface and Abstract class

Primary Difference between an Interface and an Abstract class.

• an abstract class can have a mix of abstract and non-abstract methods, so some default implementations can be defined in the
abstract base class. An abstract class can also have static methods, static data, private and protected methods, etc. In other words, a
class is a class, so it can contain features inherent to a class. The downside to an abstract base class, is that since their is only single
inheritance in Java, you can only inherit from one class.
• an interface has a very restricted use, namely, to declare a set of public abstract method singatures that a subclass is required to
implement. An interfaces defines a set of type constraints, in the form of type signatures, that impose a requirement on a subclass to
implement the methods of the interface. Since you can inherit multiple interfaces, they are often a very useful mechanism to allow a
class to have different behaviors in different situations of usage by implementing multiple interfaces.
It is usually a good idea to implement an interface when you have any methods that are to be overridden by some
subclass. If you then want some of the methods implemented with default implementations that will be inherited by
a subclass, then create an implementation class for the interface.
interface X {
void f();
int g();
}
class XImpl implements X {
void g() { return -1; } // default implementation for g()
}
class Y extends XImpl implements X {
void f() { ... } // provide implementation for f()
}
Note that when you invoke an abstract method using a reference of the type of an abstract class or an interface, the
method call is dynamically dispatched.
X x = new Y;
x.f(); // dynamically determines which f() to invoke, and calls Y.f(this=(Y)x);

1 comment:

  1. Hi Great Post,
    I would like to tell you that if you are infertile and want a child, you can have it. It's easy just call us or email us on
    http://www.arpitivf.com/ShowPage.aspx?ConTabID=180

    ReplyDelete

Thanks for your opinion....