-4

Possible Duplicate:
Use of Java [Interfaces / Abstract classes]

Why we use interface and abtract class and in which situation one should use abstract class and interface ?? can anyone explain this with simplest example .....

Community
  • 1
  • 1
user1722947
  • 3
  • 1
  • 5

1 Answers1

0

You want to use an Interface when you want all your sub-types to implement different specific logic, like in this case:

interface GeometricalShape{
      # only abstract methods are allowed
      GetArea();
      GetPerimeter();
}

In this case each geometric shape will have to implement specific logic to calculate Area and Permimeter.

You want to use an Abstract Class when although your sub-types have to implement some specific logic, you still have logic common to all sub-types like in this case:

abstract class GeometricalShape{
      name;edgeCount;
      protected GeometricalShape(name,edgeCount)

      #abstract methods
      abstract GetArea();
      abstract GetPerimeter();

      #Concrete methods
      GetName(){return name;}
      GetEdgesCount(){return edgesCount}

In this example each geometric shape will have to implement specific logic regarding Area and Perimeter like before, but now all sub-types will share common methods for retrieving the name and edge count of the geometrical, which would be redundant to be defined in each and every sub-class.

Andrei
  • 289
  • 1
  • 6
  • need some more clarity.....we can also have common properties in interface as well – user1722947 May 16 '12 at 12:12
  • You cannot define Non-Abstract methods on an interface. Observer the difference between the abstract method GetArea() which has different logic in each subclass opposed to GetName() which will behave the same in all subclasses. – Andrei May 16 '12 at 12:17
  • I edited my answer so now I hope that you understand better the difference that the interface can only allow abstract methods, whereas the abstract class allows abstract methods but also concrete methods. – Andrei May 16 '12 at 12:23
  • i know this difference and other diff also between interface and abstract class but IN WHICH SITUATION one should go for interface and and go for abstract class – user1722947 May 16 '12 at 12:27
  • In the situation where sub-classes CAN SHARE THE SAME LOGIC and using an interface would mean redundant duplicate code in all sub-classes instead of implementing and using the code from a common supper-class. It's a matter of feeling when it's right to use one or the other. There are no strict rules besides making good code that is readable, efficient and adherent to OOP practices. – Andrei May 16 '12 at 12:32
  • can anybody explain with simplest example/situation....so that i can understand in which situation i should use abstract class/interface – user1722947 May 17 '12 at 06:51