EJB design: Abstract class & interface
given an abstract class & an interface which one is more suitable to use & why. There is no need of multiple or multilevel inheritance. Is there any advantage of using interface over abstract class other than multiple inheritance ????
- Posted by: Yatish Porwal
- Posted on: September 23 2003 06:57 EDT
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
Many developers forget that a class that defines an abstract method can call that method as well.
I love this particular characteristic, because it allows me to define an overall behavior without having to worry about the concrete differences of implementation.
For example, I can create an Item class with an abstract getPrice() method. Today I can access a simple table to get the price, but tomorrow I may need to do a lookup against a "special sale price" table. These sorts of things can be added to the design completely transparently to anybody using the Item class.
Read Josh Bloch's book, "Effective Java"
He discusses this issue on pages 84 and 89
I could not find the bokk named "Effective Java" , can u please help me to find it out.
One more thing nobody has written any thing over interfaces , at least provide some drawbacks of using interface.