Why can't an abstract class extend an interface?

I'm just wondering why the abstract class cannot extend the interface .

Since we cannot instantiate the abstract class, can I simply extend the interface and then override these methods in classes that extend the abstract class?

for instance

 abstract class AbstractClass extends InterfaceA { } interface InterfaceA { public void methodToBeImplemented(); } class MyClass extends AbstractClass { @Override public void methodToBeImplemented(){ //do something } } 
+6
source share
3 answers

Since you are not extends interface - you are implements .

 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 like any other. Only interfaces can extends other interfaces.

+13
source

In fact, you can extend interfaces in Java, but it will still be called an interface.

Then you can use this advanced 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 ... } 

Right, this is exactly how the designers designed it. It goes back to the philosophy of Java and how to use classes and interfaces. Suppose you have the following classes: Student, Professor, Employee, Technician. And the following interfaces: demography, Paydetails and Personaldetails.

Ideally, a professor of classes and a technician can be expanded from a class member, and that makes sense. However, imagine how to extend a class of techniques from demographics or personal data. It does not make sense. Its like an extension of the class sky from class blue. Just because you can do it doesn’t mean you have to do it. However, it makes sense to have a class specialist from the staff and implement interfaces such as Paydetails or demographics. Its like an extension of the sky from nature, but the implementation of the interface is blue (gives it the functionality of blue).

This is the main reason Java developers opposed multiple inheritance (as opposed to cpp) and used interfaces instead. In your question, it doesn't matter if the class is abstract or not. You simply cannot expand from the interface because it does not make sense logically.

+5
source

in an interface extends only the interface. When we use an interface in a class, then it must implement in the class. Another thing is an abstract class that contains both an abstract and non-abstract method, while an interface contains only an abstract method that determines where the implementation is inteface (subclass).

0
source

Source: https://habr.com/ru/post/973578/


All Articles