Choose Your Language

Saturday, 25 May 2013

Abstract class vs Interface

Abstract class vs Interface

         An abstract class can have shared state or functionality. An interface is only a promise to
provide the state or functionality. A good abstract class will reduce the amount of code that has
to be rewritten because it's functionality or state can be shared. The interface has no defined
information to be shared

        In java you can inherit from one (abstract) class to "provide" functionality and you can
implement many interfaces to "ensure" functionality

A simple three line concept

            Use an abstract class when you want to inherit only from the parent

            Use an interface when you want to inherit from multiple sources

            Use both when you want a basic behavior from the parent and extra features from other
                sources

Is there a performance overhead in using either an abstract class or an
interface?


         Abstract class is faster than interface.
       
example:

abstract class shape
                 {
                   int a,b,c;
                   String s1;
                   abstract area(int);
                   abstract area(int a, string s);
                 }

 Why we are? and when we are using Interfaces ?      

               Interfaces are useful when you do not want classes to inherit from unrelated classes just     
to get the required functionality. For example, let bird be a class with a method fly(). It will be
ridiculous for an aeroplane to inherit from bird class just because it has the fly() method. Rather
the fly() method should be defined as an interface and both bird and aeroplane should implement
that interface.

When should I use an interface instead of an abstract class

            Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.

            Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts.

   E.g. In an application there are different editors. There are different toolbars, which can be used on these editors like navigation tool bar. In order to use this tool bar editor should implement that functionality.

So there can be interfaces like - navigation - search – save and modify if an editor implements all three all toolbars will be enabled. if one then only one will be enable. and implementation of these interface differs from context to context.

In the same example myAbstractEditor can be a class, which implements basic functionality of the editor. Where setting different controls, getting values from them can be abstract, which will depend on editor to editor.
          

No comments:

Post a Comment