15

I was thinking about that, and I had some doubts.

When I declare an interface, for example:

public interface MyInterface
{
   public void method1();
   public void method2();
}

Could these interface methods be considered abstract? What I mean is that the concept of an abstract method is:

An abstract method is a method that is declared, but contains no implementation.

So, could these methods be considered abstract? They are not "pure" abstract methods as I'm not using the abstract word, but conceptually, it looks like they are.

What can you tell me about it?

Thanks.

rogcg
  • 385

6 Answers6

13

An interface is like a "purely" abstract class. The class and all of its methods are abstract. An abstract class can have implemented methods but the class itself cannot be instantiated (useful for inheritance and following DRY).

For an interface, since there isn't any implementation at all they are useful for their purpose: a contract. If you implement the Interface then you must  implement the methods in the interface.

So the difference is an abstract class can have implemented methods whereas a interface cannot.

The reason they are separate is so a class can implement several interfaces. Java and C# restrict a class to inherent from a single parent class. Some languages allow you to inherit from multiple classes and you could accomplish the work of an interface via a "purely" abstract class. But multiple inheritance has its problems, namely the dreaded Diamond Problem

coder
  • 2,019
11

I found an usefull answer here: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

All of the methods in an interface are implicitly abstract, so the abstract modifier is not used with interface methods (it could be—it's just not necessary).

rogcg
  • 385
4

Abstract classes can have abstract methods.

Interfaces can only have abstract methods.

method1() and method2() in your example are abstract methods.

p.s.w.g
  • 4,215
Tulains Córdova
  • 39,570
  • 13
  • 100
  • 156
-1

The difference here is that abstract classes can contain implementation details, although cannot be instantiated by themselves. Whereas an interface is merely a template for a class

billy.bob
  • 6,569
-2

So in a subclass, inherited abstract method can again go abstract without implementation , while if a class implements an interface it's method must be implemented.

-3

Interface classes don't have abstract methods. They don't have any methods at all. They just have a list of methods that another class would have to implement to be able to conform to the interface. In your example, there is no method method1 and no method method2 until someone adds these methods to a class.

gnasher729
  • 49,096