Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an abstract class extend an interface?

I was just wondering why an abstract class can't extend an interface.

Since we can't instantiate an abstract class, can't I just extend the interface and then override those methods in the classes which are extending the abstract class?

For example

abstract class AbstractClass extends InterfaceA 
{

}

interface InterfaceA
{
   public void methodToBeImplemented();
}

class MyClass extends AbstractClass
{
  @Override
  public void methodToBeImplemented(){
      //do something
  }
}  
like image 296
Praveen Reddy Katta Avatar asked Aug 09 '14 00:08

Praveen Reddy Katta


People also ask

Can abstract class extend an interface?

Multiple implementations: An interface can extend one or more Java interfaces; an abstract class can extend another Java class and implement multiple Java interfaces.

Does an abstract class extend or implement an interface?

An abstract class permits you to make functionality that subclasses can implement or override whereas an interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces.

Why an interface is not extended by a class?

What's the reason? A class can't extend an interface because inheriting from a class ( extends ), and implementing an interface ( implements ) are two different concepts. Hence, they use different keywords.

Can you extend from an abstract class?

An abstract class can extend another abstract class. And any concrete subclasses must ensure that all abstract methods are implemented. Abstract classes can themselves have concrete implementations of methods. These methods are inherited just like a method in a non-abstract class.


2 Answers

Because you don't extends an interface - you implements it.

interface InterfaceA
{
   public void methodToBeImplemented();
}

abstract class AbstractClass implements InterfaceA 
{

}

class MyClass extends AbstractClass
{
  @Override
  public void methodToBeImplemented(){
      //do something
  }
}  

An abstract class is still a class, just like any other. Only interfaces can extends other interfaces.

like image 122
Qix - MONICA WAS MISTREATED Avatar answered Sep 21 '22 15:09

Qix - MONICA WAS MISTREATED


in interface extends only interface .when we use a interface in a class then it need to implements in class.and another thing is abstract class contain a both abstract and non abstract method while interface contain only abstract method that are define where implementation of inteface(subclass).

like image 25
anjli Avatar answered Sep 20 '22 15:09

anjli