C# .NET - Interface and Abstract Class

Asked By kishore Devalla on 04-Aug-11 02:04 PM
Hai,

When do we go for Interface..When do we go for Abstract Class...Give one example
Today i faced one interview ..He asked this question.I want answer with Example

Thanks in Advance
Web Star replied to kishore Devalla on 04-Aug-11 02:10 PM

Abstract Class ::
- It cannot defines all the methods
- It has subclass.
- Here, Subclass is useless
- A class can be extend an abstract class


Interface ::
- It defines all the methods
- It must have implementations by other classes, But there will be no use of that.
- Only an interface can extend another interface.


For More details..


http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/8ad621b8-a915-4d7e-89c3-5dbbc47202fd/


http://kyapoocha.com/c-sharp-interview-questions/what%E2%80%99s-the-difference-between-an-interface-and-abstract-class-5/


http://www.dotnetuncle.com/Difference/4_abstract_class_interface.aspx


Hope this helps.

Ravi S replied to kishore Devalla on 04-Aug-11 02:17 PM
HI

An interface contains only the signatures of http://msdn.microsoft.com/en-us/library/ms173114(v=vs.80).aspx, http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx or http://msdn.microsoft.com/en-us/library/awbftdfh(v=vs.80).aspx.

 The implementation of the methods is done in the class that implements the interface, as shown in the following example:

      interface ISampleInterface
{
    void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }
    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();
        // Call the member.
        obj.SampleMethod();
    }
}

Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error.

When you need a part of the class to be implemented. The best example I've used is the http://www.dofactory.com/Patterns/PatternTemplate.aspxpattern.

public abstract class SomethingDoer
{
    public void Do()
    {
        this.DoThis();
        this.DoThat();
    }
    protected abstract void DoThis();
    protected abstract void DoThat();
}

Thus, you can define the steps that will be taken when Do() is called, without knowing the specifics of how they will be implemented. Deriving classes must implement the abstract methods, but not the Do() method.

Extensions methods don't necessarily satisfy the "must be a part of the class" part of the equation. Additionally, iirc, extension methods cannot (appear to) be anything but public in scope.

edit

The question is more interesting than I had originally given credit for. Upon further examination, Jon Skeethttp://stackoverflow.com/questions/783312/interface-extension-mixin-vs-base-class a question like this on SO in favour of using interfaces + extension methods. Also, a http://stackoverflow.com/questions/299515/c-reflection-to-identify-extension-methods is using reflection against an object hierarchy designed in this way.

Personally, I am having trouble seeing the benefit of altering a currently common practice, but also see few to no downsides in doing it.

It should be noted that it is possible to program this way in many languages via Utility classes. Extensions just provide the syntactic sugar to make the methods look like they belong to the class.

refer the links also

http://csharp.net-tutorials.com/classes/abstract-classes/

http://www.csharp-station.com/Tutorials/Lesson13.aspx

http://www.codeproject.com/KB/cs/cs_interfaces.aspx

http://www.dotnetspider.com/forum/13184-OOPS-Why-we-need-an-Interface.aspx

dipa ahuja replied to kishore Devalla on 04-Aug-11 02:24 PM
These are the difference between abstract class and Interface , read them and you may get idea where to choose what:

(1)  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface cannot implement methods.
 
(2)  An abstract class can contain fields, constructors, or destructors and implement properties. An interface cannot contain fields, constructors, or destructors and it has only the property's signature but no implementation.
 
(3)  An abstract class cannot support multiple inheritances, but an interface can support multiple inheritances. Thus a class may inherit several interfaces but only one abstract class.
 
(4)  A class implementing an interface has to implement all the methods of the interface, but the same is not required in the case of an abstract Class.
 
(5)  Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces. 
 
(6) Abstract classes are are faster than interfaces.
 

 

Reena Jain replied to kishore Devalla on 04-Aug-11 02:36 PM
Hi,

here are some good point which i would like to share with you

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.


Hope this will help you
Radhika roy replied to kishore Devalla on 04-Aug-11 02:57 PM

Interfaces

This lesson teaches C# Interfaces. Our objectives are as follows:

  • Understand the Purpose of Interfaces.
  • Define an Interface.
  • Use an Interface.
  • Implement Interface Inheritance.

An interface looks like a class, but has no implementation. The only thing it contains are definitions of eventsindexersmethods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined.

So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

Because interfaces must be implemented by derived classes and structs, they define a contract. For instance, if class foo implements the IDisposable interface, it is making a statement that it guarantees it has the Dispose() method, which is the only member of the IDisposable interface. Any code that wishes to use class foo may check to see if class foo implementsIDisposable. When the answer is true, then the code knows that it can call foo.Dispose(). Listing 13-1 shows how to define an interface:

Listing 13-1. Defining an Interface: MyInterface.cs

interface IMyInterface
{
    void MethodToImplement();
}

Listing 13-1 defines an interface named IMyInterface. A common naming convention is to prefix all interface names with a capital "I". This interface has a single method namedMethodToImplement(). This could have been any type of method declaration with different parameters and return types. I just chose to declare this method with no parameters and avoid return type to make the example easy. Notice that this method does not have an implementation (instructions between curly braces - {}), but instead ends with a semi-colon, ";". This is because the interface only specifies the signature of methods that an inheriting class or struct must implement. Listing 13-2 shows how this interface could be used.

Listing 13-2. Using an Interface: InterfaceImplementer.cs

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
      InterfaceImplementer iImp = 
new InterfaceImplementer();
      iImp.MethodToImplement();
    }

    public
 void MethodToImplement()
    {
      Console.WriteLine("MethodToImplement() called.");
    }
}

The InterfaceImplementer class in Listing 13.2 implements the IMyInterface interface. Indicating that a class inherits an interface is the same as inheriting a class. In this case, the following syntax is used:

class InterfaceImplementer : IMyInterface

Now that this class inherits the IMyInterface interface, it must implement its members. It does this by implementing the MethodToImplement() method. Notice that this method implementation has the exact same signature, parameters and method name, as defined in the IMyInterface interface. Any difference between the method signature in the interface and the method signature in the implementing class or struct will cause a compiler error. Additionally, a class or struct that inherits an interface must include all interface members; You will receive a compiler error if you don't implement all interface members.

Interfaces may also inherit other interfaces. Listing 13-3 shows how inherited interfaces are implemented.

Listing 13-3. Interface Inheritance: InterfaceInheritance.cs

using System;

interface IParentInterface
{
    void ParentInterfaceMethod();
}

interface
 IMyInterface : IParentInterface
{
    void MethodToImplement();
}

class
 InterfaceImplementer : IMyInterface
{
    static void Main()
    {
      InterfaceImplementer iImp = 
new InterfaceImplementer();
      iImp.MethodToImplement();
      iImp.ParentInterfaceMethod();
    }

    public
 void MethodToImplement()
    {
      Console.WriteLine("MethodToImplement() called.");
    }

    public void ParentInterfaceMethod()
    {
      Console.WriteLine("ParentInterfaceMethod() called.");
    }
}

The code in listing 13.3 contains two interfacesIMyInterface and the interface it inherits, IParentInterface. When one interface inherits another, any implementing class or struct must implement every interface member in the entire inheritance chain. Since the InterfaceImplementer class in Listing 13-3 inherits from IMyInterface, it also inherits IParentInterface. Therefore, the InterfaceImplementer class must implement the MethodToImplement() method specified in the IMyInterface interface and the ParentInterfaceMethod() method specified in the IParentInterface interface.

Summary

You now understand what interfaces are. You can implement an interface and use it in a class. Interfaces may also be inherited by other interface. Any class or struct that inherits aninterface must also implement all members in the entire interface inheritance chain.

Introduction

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don�t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:

abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:

abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have anabstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

using System;
namespace abstractSample
{
      //Creating an Abstract Class

      abstract class absClass
      {
            //A Non abstract method

            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }
            //An abstract method, to be

            //overridden in derived class

            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }
      //A Child Class of absClass

      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an

               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }
            //using override keyword,

            //implementing the abstract method

            //MultiplyTwoNumbers

            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers andMultiplyTwoNumbersAddTwoNumbers is a non-abstract method which contains implementation andMultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers andMultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the childclass it is optional to make the implementation of the abstract methods of the parent class.

Example

//Abstract Class1

abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}
//Abstract Class2

abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers

    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}
//Derived class from absClass2

class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers

    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}

In the above example, absClasscontains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived fromabsClass2 and the MultiplyTwoNumbers is implemented there.

Abstract properties

Following is an example of implementing abstract properties in a class.

//Abstract Class with abstract properties

abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}
class absDerived:absClass
{
    //Implementing abstract properties

    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.

Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.

//Incorrect

abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.

An abstract method cannot be private.

//Incorrect

private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.

//Incorrect

public abstract virtual int MultiplyTwoNumbers();

An abstract member cannot be static.

//Incorrect

publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

An example of interface:

interface iSampleInterface
{
  //All methods are automaticall abstract

  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.

The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

class can inherit one or more interfaces, but only one abstract class.

Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can make anabstract class, interface or combination of both depending on your needs.

Devil Scorpio replied to kishore Devalla on 04-Aug-11 03:35 PM
Hi,

In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

The difference between abstract classes and interfaces have been explained in detail with code sample in the following link. I would suggest you to go through this link and I find this as one of the best explanations to understand their differences:

http://www.codeproject.com/csharp/AbstractsVSInterfaces.asp

http://www.codeproject.com/csharp/AbstractsVSInterfaces.asp

also look into the following msdn link too

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1235498&SiteID=1

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1235498&SiteID=1

Use an abstract class when

·      When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)

·      Use an abstract class to define a common base class for a family of types.

·      Use an abstract class to provide default behavior.

·      Subclass only a base class in a hierarchy to which the class logically belongs.

Use an interface when

·      When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.

·      Use an interface to design a polymorphic hierarchy for value types.

·      Use an interface when an immutable contract is really intended.

·      A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

Irfan Khan replied to kishore Devalla on 04-Aug-11 04:13 PM

Abstract Class vs Interface

I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.

We cannot make instance of Abstract Class as well as Interface.

Here are few differences in Abstract class and Interface as per the definition.

Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.

 //Abstarct Class

public abstract class Vehicles

    {

    private int noOfWheel;

    private string color;

    public abstract string Engine

    {  

      get;

      set;

    }

    public abstract void Accelerator();

    }

 //Interface

public interface Vehicles

    {

    string Engine

    {  

      get;

      set;

    }

    void Accelerator();

    }

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.

We use abstract class and Interface for the base class in our application.

This is all about the language definition. Now million dollar question:

How can we take decision about when we have to use Interface and when Abstract Class.

Basically abstact class is a abstract view of any real-world entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implementation. Intention means I know about the entity and  also may have idea about its state as well as behavior but don’t know about how its looks or works or may know partially. Implementation means actual state and behavior of entity. 

Enough theory let’s take an example.

I am trying to make a Content Management System where content is a generalize form of article, reviews, blogs etc.

CONTENT

ARTICLE

BLOGS

REVIEW

So content is our base class now how we make a decision whether content class should be Abstract class, Interface or normal class.

First normal class vs other type (abstract and interface). If content is not a core entity of my application means as per the business logic if content is nothing in my application only Article, Blogs, Review are the core part of business logic then content class should not be a normal class  because I’ll never make instance of that class. So if you will never make instance of base class then Abstract class and Interface are the more appropriate choice.

Second between Interface and Abstract Class.

CONTENT

Publish ()

ARTICLE

BLOGS

REVIEW

As you can see content having behavior named “Publish”. If according to my business logic Publish having some default behavior which apply to all I’ll prefer content class as an Abstract class. If there is no default behavior for the “Publish” and every drive class makes their own implementation then there is no need to implement “Publish” behavior in  the base case I’ll prefer Interface.

These are the in general idea of taking decision between abstract class, interface and normal class. But there is one catch. As we all know there is one constant in software that is “CHANGE”. If I made content class as Interface then it is difficult to make changes in base class because if I add new method or property in content interface then I have to implement new method in every drive class. These problems will overcome if you are using abstract class for content class and new method is not an abstract type. So we can replace interface with abstract class except multiple inheritance.

CAN-DO and IS-A relationship is also define the deference between Interface and abstract class. As we already discuss Interface can be used for multiple inheritance for example we have another interface named “ICopy” which having behavior copy and every drive class have to implements its own implementation of Copy. If “Article” class drive from abstract class Content as well as ICopy then article “CAN-DO” copy also.

IS-A is for “generalization” and “specialization” means content is a generalize form of Article, Blogs, Review and Article, Blogs, Review are a specialize form of Content.

So, abstract class defines core identity. If we are thinking in term of speed then abstract is fast then interface because interface requires extra in-direction.

So as per my view Abstract class having upper-hand in compare to interface. Using  interface having only advantage of multiple inheritance. If you don’t understand the things then don’t worry because it’s my mistake because I am not able to describe the topic.

For more info you visit, I hope that may more help you.

http://codeofdoom.com/wordpress/2009/02/12/learn-this-when-to-use-an-abstract-class-and-an-interface/

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx


Jitendra Faye replied to kishore Devalla on 05-Aug-11 12:09 AM

What is an Abstract Class?
 

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.


What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn?t support multiple inheritance, interfaces are used to implement multiple inheritance.


Virtual?
Virtual is a keyword, which is used for indecating that particular method can be override.


For more detail follow this link--

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

I hope this will help you.

Golu sharma replied to kishore Devalla on 05-Aug-11 01:07 AM
//Abstarct Class

public abstract class Vehicles

      {

      private int noOfWheel;

      private string color;

      public abstract string Engine

      {  

        get;

        set;

      }

      public abstract void Accelerator();

      }

    //Interface

public interface Vehicles

      {

      string Engine

      {  

        get;

        set;

      }

      void Accelerator();

      }

 

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.

We use abstract class and Interface for the base class in our application.

 

This is all about the language defination. Now million doller question:

How can we take decision about when we have to use Interface and when Abstract Class.

Basicly abstact class is a abstract view of any realword entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implemntation. Intention means I know about the entity and  also may have idea about its state as well as behaviour but don’t know about how its looks or works or may know partially. Implementation means actual state and behaviour of entity.  

Enough theory lets take an example.

Golu sharma replied to kishore Devalla on 05-Aug-11 01:08 AM
This link is best for you

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Golu sharma replied to kishore Devalla on 05-Aug-11 01:10 AM
Deeply learn Abstract class

Abstract Class in java

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.

A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

<br /><font size=-1>

abstract class Vehicle {
	int numofGears;
	String color;
	abstract boolean hasDiskBrake();
	abstract int getNoofGears();
}

Example of a shape class as an abstract class

abstract class Shape {
	public String color;
	public Shape() {
	}
	public void setColor(String c) {
		color = c;
	}
	public String getColor() {
		return color;
	}
	abstract public double area();
}

We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

public class Point extends Shape {
	static int x, y;
	public Point() {
		x = 0;
		y = 0;
	}
	public double area() {
		return 0;
	}
	public double perimeter() {
		return 0;
	}
	public static void print() {
		System.out.println("point: " + x + "," + y);
	}
	public static void main(String args[]) {
		Point p = new Point();
		p.print();
	}
}

Output

point: 0, 0

Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class.

The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.

A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

Golu sharma replied to kishore Devalla on 05-Aug-11 01:11 AM
Deeply learn Interface class

Java Interface

In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.

Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.

Example 1: Below is an example of a Shape interface

interface Shape {
	public double area();
	public double volume();
}

Below is a Point class that implements the Shape interface.

public class Point implements Shape {
	static int x, y;
	public Point() {
		x = 0;
		y = 0;
	}
	public double area() {
		return 0;
	}
	public double volume() {
		return 0;
	}
	public static void print() {
		System.out.println("point: " + x + "," + y);
	}
	public static void main(String args[]) {
		Point p = new Point();
		p.print();
	}
}
Golu sharma replied to kishore Devalla on 05-Aug-11 01:14 AM
Abstract :
=========================================
1. Abstract class cannot be instantiated.
2. Abstract class may contain abstract methods and accessors.
3. Abstract modifier can be used with classes, methods and properties.
4. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
5. Abstract method declarations are only permitted in abstract classes.
***********************************************************
Interface :
=========================================
1.Interfaces are similar to classes.
2.They can have member properties and methods.
3.All the properties and methods of interfaces are abstract.
4.They have no body, just the declaration.
5.Public, Protected, Private, Friend, Shared, Overrides, MustOverride, NotOverridable are permitted inside an interface.
---

Abstract Class
===========
Here inheritance is possible, instantiating object is not possible
The Abstract class Abstract method will be implement only in derived class by OVERRIDE.
At least one Abstract method is must and should in Abstract Class.



Interface
=======
It’s a pure abstract class.
It has only Abstract methods no implementation. Implement methods through class.

Can inherit can’t create object to interface.

Public Access modifier not private

It’s a indicator. It indicates what, class must provide after inherited the interface. OVERRIDE no need.

Multiple inheritance is possible through Interface only in C#.
Radhika roy replied to kishore Devalla on 05-Aug-11 12:50 PM

Diffrence between abstract and interface...

Abstract class Interface
Derived classes exhaust their single base class inheritance option. Classes can implement multiple interfaces without using up their base class option. But, there are no default implementations.
Cannot be instantiated except as part of subclasses. Only derived classes can call an abstract class constructor. Cannot be instantiated.
Defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract. Defines abstract member signatures—all of which—implementing classes must implement. Otherwise, a compiler error results.
New non-abstract members may be added that derived classes will inherit without breaking version compatibility. Extending an interface with new members breaks version compatibility.
Optionally, provide default (virtual) member implementation. All members are virtual and cannot provide implementations.
Can include data fields. Cannot include data fields. However, abstract properties may be declared.


By seeing difference you can know that what you want to use.


Hope this will help you.