简体   繁体   中英

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
  }
}  

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.

You can actually extend interfaces in Java, but it would still be called an interface.

Then you can use this extended interface implemented in your abstract class.

interface InterfaceName
{
    public void foo();
}

public interface ExtendedInterface extends InterfaceName
{
    public void bar();
}

public class ClassName implements ExtendedInteface 
{
    //implementation for all methods in InterfaceName and ExtendedInteface
    ...
}

Praveen, its just the way the designers designed it. It goes back to the philosophy of Java and the way classes and interfaces are meant to be used. Lets say you have following classes: Student, Professor, Employee, Technician. And following interfaces: Demography, Paydetails and Personaldetails.

Ideally, classes professor and technician can be both extended from the class employee and it makes sense. However, imagine extending class Technician from Demography or Personaldetails. It doesnt make sense. Its like extending class sky from class blue. Just cause you can do doesnt mean you should do it. However, it makes more sense to have a class technician extend from employee and implement interfaces like Paydetails or demography. Its like extending sky from nature but implementing interface blue (giving it function capabilities of blue).

This is the basic reason why Java developers were against multiple inheritance (unlike cpp) and instead use interfaces. In your question, it doesnt matter if the class is abstract or not. You simple cant extend from an interface cause it does not make sense logically.

in接口只扩展接口。当我们在类中使用接口时,它需要在类中实现。另一件事是抽象类同时包含抽象和非抽象方法,而接口仅包含定义inteface()实现位置的抽象方法。子类)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM