Friday 6 January 2012

Java Concepts: Interface and Abstract class

Interface - Interface is nothing but a way of achieving abstraction.There is a drawback in java that it does not allow multiple inheritance.To overcome the problem of multiple inheritance ,concept of interfaces is applied. Interface consist of a set of instance and abstract method prototype(by default public must).When a class wants to use that method than it must be implement that interface and also provide the body of the method.Some more facts about Interface:
  1. Interfaces can't be initiated means we can not form a object of Interface.
  2. variables of interface are public,static and final (by default).
  3. One class may implement more than one interfaces.
  4. One interface can extend other interface.
Example: public interface drawable{   // defining interface.
                    public void draw(Graphics g);
               }
             public class Line implements drawable  { //Implementation.
                  public void draw(Graphics g){
                        .......................
                       .........................
             }

Abstract Class- It is also a way of achieving abstraction.An abstract class is one that is not used to construct  Object , it is used as a base for making subclass.An Abstract class is exist only to express common properties  of all its sub classes.Some important properties of abstract class:

  1. Abstract class can't be initiated means its object can not be formed.
  2. Abstract and non-abstract both kind of method are put into abstract class.
  3. Non-abstract method must declare their body in abstract classes.  
Example: abstract class Base{                    //declare
                               abstract void show();
                   }
               class Child extends Base{             //Implementation
                          void show()
                                       {..........................
                                        ..........................;
                                      }
             }

    No comments:

    Post a Comment