Search on this Website

Thursday, June 28, 2007

Abstract Vs Interfaces

abstract
An formally unfinished class or method, marked with the keyword abstract. It is a way of preventing someone from instantiating a class that is supposed to be extended first. An abstract class is deliberately missing some or all of the method bodies. An abstract method is deliberately missing its method body. An abstract class is similar to an interface which is missing all the method bodies. An abstract class provides a base for someone to extend an actual class. You can't use new on abstract classes, but you can use abstract references, which always point to objects of a class that extends the abstract class. Interfaces are implicitly abstract as are all their methods.




To use make practical use of an abstract class, you must define a non-abstract class that extends the abstract one. It can use any of the inherited non-abstract methods. It must implement any of the abstract ones.
Sometimes a abstract class may extend another abstract class. In that case it need not implement all the non-abstract methods.

Interfaces
Under the hood, an interface is like a class with some restrictions.
1. All its methods must be abstract instance methods, no static methods allowed.
2. Yet, all the variables defined in an interface must be static final, i.e. constants. Happily the values need not be known at compile time. You can do some computation at class load time to compute the values. The variables need not be just simple ints and Strings. They can be any type.
3. No static initialiser blocks. You must do your initialisations in one line per variable. And, of course, no static initialiser helper methods defined in the interface. If you need them, them must be defined outside the interface.

Instantiating
interface methods are always instance methods. To use them, there must be some associated Object that implements the interface. You can't instantiate an interface directly, but you can instantiate a class that implements an interface. References to an Object can by via the class name, via one of its superclass names, or one of its interface names.
Under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them?
Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the language and object-oriented programming in general
Yes, other non abstract methods can access a method that you declare as abstract.
But first, let's look at when to use normal class definitions and when to use interfaces. Then I'll tackle abstract classes.

To be Continued.....

Designed By Srikanth Vadlamani

No comments: