Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do/can abstract classes replace interfaces? [duplicate]

Tags:

In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?

like image 353
Registered User Avatar asked Jan 23 '10 22:01

Registered User


People also ask

Can abstract class override 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.

Can abstract class implement more than two interfaces?

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

What makes abstract classes different from interfaces?

The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

Are interfaces the same as abstract classes?

Differences between abstract classes and interfaces. From an object-oriented programming perspective, the main difference between an interface and an abstract class is that an interface cannot have state, whereas the abstract class can have state with instance variables.


1 Answers

Not always:

  • a class can extend only one class
  • a class can implement more than one interface

Sun docs make a more detailed comparison:

Abstract Classes versus Interfaces

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

like image 140
Bozho Avatar answered Oct 07 '22 14:10

Bozho