Home computickets Abstract class and interface

Abstract class and interface

Author

Date

Category

What are the differences between an abstract class and an interface?


Answer 1, authority 100%

A short distinction.

An abstract class is a class that does not have one or more methods implemented (some languages ​​require such methods to be marked with special keywords).

An interface is an abstract class with none methods implemented, all of them are public and there are no class variables.

An interface is usually needed when only an interface is described (tautology). For example, one class wants to give another the ability to access some of its methods, but does not want to “reveal” itself. So it just implements the interface.

An abstract class is needed when you need a family of classes that have a lot in common. Of course, you can use the interface, but then you will need to write a lot of identical code.

In some languages ​​(C++) there is no special keyword to denote interfaces.

Any interface can be considered an abstract class, but not vice versa.


Answer 2, authority 46%

tl; dr: An abstract class is a low-level class development tool, a tool for code reuse; an interface is a means of expressing the semantics of a class. Thus, these are completely different, little related concepts.


Think about it differently.

Abstract class is a “stub” of a class: most of the methods (including internal ones) are implemented, except a few. These few unimplemented methods may well be internal methods of the class, they only clarify the implementation details. An abstract class is a facility for code reuse, a facility for specifying which method must be overridden to complete the writing of the class.

Interface is a kind of contract: interfaces are used in definitions to indicate that the object that will actually be used should implement (for input parameters) or will be guaranteed to implement (for output parameters) a set of methods and (more importantly!) have certain semantics. The interface may well be empty, however, to implement the interface means to support this semantics.

Abstract classes are ideologically similar to templates C++: both are prefabricated classes, but the template needs to specify the template types to get the class, and the abstract class needs to specify abstract methods.

Interfaces are ideologically similar to C++ header files: they expose methods and hide a specific implementation.

The question of whether an interface or an abstract class is actually a class is a technical implementation detail that depends on a particular programming language. For example, in C++ there are no interfaces at all, and they have to be emulated with classes without data. There is no abstract class in C++ as such either, but it can be considered any class with abstract methods. (Hence the C++ limitation: at least 1 abstract method in an abstract class.) Also in C++, you can (indirectly) instantiate an abstract class, call an abstract method, and (possibly) get a runtime error. In C #, interfaces and abstract classes are built into the language.


Example (in C #, the specific language does not matter):

// common code for all animals
abstract class Abstract
{
  public int Age {get; protected set; }
  public int Weight {get; protected set; }
  public bool Sleeping {get; protected set; }
  public void SubmitVoice ()
  {
if (! Asleep & amp; & amp; Age & gt; Age CutVoice)
      ImplementationSubmitVoice ();
  }
  abstract protected void ImplementationSubmitVoice ();
  readonly protected int Age of CutVoice;
}
class Dog: Abstract
{
  override protected void ImplementationSubmitVoice ()
  {
    Woof ();
  }
  public void woof ()
  {
    // implementation
  }
  public Dog () {VoiceCut Age = 2; }
}
class Cat: Abstract
{
  override protected void ImplementationSubmitVoice ()
  {
    Meow();
  }
  public void Meow ()
  {
    // implementation
  }
  public Cat () {VoiceCut Age = 1; }
}

interface Ianimal
{
  int InventoryNumber {get; }
}
class Lion: Zoo Dweller, Animal
{
  // ...
}
class Zebra: Zoo Dweller, Animal
{
  // ...
}
class Guardian: Zoo Dweller
{
}
// ...
void Inventory ()
{
  List & lt; Zoo Dweller & gt; inhabitants = // ...
  foreach (var dweller in dwellers)
    if (inhabitant is Ianimal) // separate animals from non-animals
      Add Animal ((I Animal) inhabitant);
}
void AddAnimal (IAnimal) // only an animal can get here
{
  ...

Answer 3, authority 36%

I find it curious enough that this question is tagged “oop”, but at the same time, in many answers, specific aspects of specific programming languages ​​are clearly leaking out. I will try to give an answer based on the concepts of OOP and only then show why this difference appeared in some programming languages.

Abstract classes and interfaces have a certain relationship to inheritance, more precisely to modeling the world. With their help, we want to express that a certain group of things in our system has something in common: some common behavior that distinguishes this group of gizmos from all others.

For example, let’s say we want to model buttons in the user interface. Since we are talking about OOP, we will single out a certain type of Button with a certain set of operations (which determine the behavior) and a hidden state on which the behavior is based (yes, there may not be a hidden state). At the same time, we can distinguish three types of operation:

  • A specific fixed operation that must be absolutely stable for all types of buttons.

  • A specific operation with default behavior (i.e. an operation whose behavior is suitable for many types of buttons, but there may be buttons with different behavior).

  • Declaration of an operation without a specific implementation (i.e. an operation whose behavior cannot be determined, because at this stage reasonable default behavior is not known, or operations may differ too much for different buttons ).

In other words, the Button type can contain non-virtual methods , virtual methods (virtual methods), and abstract methods ( abstract methods).

Having different types of methods is a very important modeling tool and allows you to very accurately express the intent of the designer. For example, we can add a non-virtual operation “Pressing the button”, which will delegate some of its work to the virtual (or abstract method) “Handle the press”, but at the same time always perform a certain part of the work (the discerning reader will see in this description the pattern “Template method” ).

After we have defined the base type, it’s time to define arbitrary types. And here the questions begin. More precisely, no questions arise when a type has only one immediate base type, or all base types contain only operation declarations. No problem, inherit the “Menu Button” from the “Button” and override the “Press the button” method. But what if our type “Menu Button” is inherited from two types with the same virtual operation? How to override just one and keep the other? But what about a new type of client and distinguish which operation to call? What if two base types have a field with the same name? But what if one basic type has the “Press the button” method implemented, while the other has only a declaration?

No, all these problems can be solved, and in C++, Eiffel, and other programming languages, you can quite flexibly control what and how to override, what to hide, what to expose and how to call a method of a certain base type. But for the authors of some programming languages, such complexity seemed unnecessary, and they went for a trick and separated the types that contain only method declarations into a separate category, and this is how interfaces appeared .

It will now be easy to distinguish between the three concepts – an interface, an abstract base class, and a concrete base class.

  • Interface – describes a certain family of types and contains only declarations of operations (yes, I deliberately write the word “declaration”, and do not use the word “contract”, which in OOP has a very definite meaning ).

  • An abstract base class describes a family of types, but in addition to the declaration of operations, it can contain default implementations (virtual methods) and fixed operations (non-virtual methods).

  • Concrete class describes some family of types that are ready for use by clients. Such a class cannot contain declarations of operations and all of its operations must be either fixed (non-virtual methods) or contain a default implementation (virtual methods). There is another subtype of concrete classes – sealed class – this is a kind of a concrete class that cannot be inherited from, which means it can only contain specific operations.

Separating interfaces into a separate category is useful not only from the point of view of simplifying the implementation of programming languages, but also for highlighting different approaches to modeling. So, for example, class inheritance models the relationship “Is” (“Menu button” IS “Button”), and base classes usually contain certain functionality that is closely related to the functionality of the derived class. Base classes not only model a group of types, but also allow you to reuse existing functionality.

Interfaces, by their very nature, have less coupling (low coupling), since they do not have specific behavior that can complicate the life of a descendant class. Interfaces can also model the Is relationship (Menu Button IS Ibutton), but they can define a less rigid CAN DO (CAN DO) relationship. For example, the BCL’s IEquatable interface defines “additional” behavior that indicates that types can compare object values.


Answer 4, authority 11%

Differences between an abstract class and an interface in Java

is used to define an abstract class

keyword is used to define an interface

keyword

keyword is used to implement the interface

Abstract Class Interface
Keyword used to describe The keyword abstract The interface
Keyword used for implementation To inherit from an abstract class, use the extends The implements
Constructor Constructor definition allowed Declaration / definition of constructor is prohibited
Default Methods Implementation Allowed Up until Java 8, only method declarations were allowed, but their implementation was not allowed. Starting with Java 8, the implementation of static methods became valid, and the implementation of non-static methods became available through the keyword default
Fields May have both static and non-static fields (the same applies to final) Any interface fields by default are public static final (and cannot have any other)
Access Modifiers Members of an abstract class can have any access modifier: public , protected , private , or the default access modifier (package ) Interface members are public by default (and cannot have any other access modifier) ​​
Inheritance May extend (extends ) any other class and implement (implements ) no more than 65535 interfaces May extend (extends ) no more than 65535 interfaces

Answer 5, authority 11%

Let’s go in order. The Interface is a contract / commitment that a class takes on and is obligated to fulfill. Let’s say: there is an array of classes that know how to say hello

std :: vector & lt; IHellower * & gt; mArr;
class IHellower {
   virtual void Hello () = 0;
}

Now any class, regardless of its hierarchy complexity and volume, can inherit (take upon itself the obligation / sign a contract for execution) of this method and thus “become its own through strangers”. The best part is that no matter how extensive the interface (in this context there are public methods of the class) for the class that fulfills this contract, only one method from this array will be seen. Example: there are many graphic classes and you have taught some of them to react to Blur – stuff them into 1 array of interfaces and, if necessary, call the Blur (int value) method;
When using the interface, we abstract from what kind of class: car, plant, air … If he has undertaken to have the implementation of “Hello” we have a guarantee that this method will be available to us through an object (a pointer to this class) (as a reminder, the interface is purely virtual methods, in the public section, without variables).

And now the other side, C++, for all its power, has no concept of an interface at the language level. But programmers are used to the interface, it is convenient, it is safe (read about Insersion of control) and correct (in terms of architecture). We have to implement the “interface” with the tools that the C++ language offers – this is an abstraction class. As you noticed, you can put various methods (public / protected / private), class members there (in other languages, there are already problems for variables in the interface). There would be an interface keyword in C++ and inherited clearly as in C # – there would be no such confusion.
Abstract classes, just, and are used in cases of allocation of a common part of classes, but the class itself, as it were, should not be (it makes no sense to have an instance of such a class).

class SomeThingLikeABall
{
    private:
      int radius;
      int weight;
    public:
      bool canPlayFootballWithIt () = 0;
      void draw () = 0;
}

As an example, they described the ball and watermelon classes, found common features, saw what else round objects will describe. We separated all this into a general class and made it abstract, because why should the system have the ability to have the class “Something is round, with weight and can be thrown”.


Answer 6, authority 9%

It can also be added that often a class describes a certain model, and an interface describes a behavior or a role. The class is called a noun (Dog, Car, House), and the -able ending is added to the interface to describe some action or property (Moveable, Eatable, Buildable). For example, we are creating a strategy game. We have different factions, each of them has different units (warriors, builders) and we create a separate class for each unit. But the behavior between all these units has a lot in common – any warrior, regardless of faction, has the ability to fight (Attackable), any builder, regardless of faction, has the ability to build (Buildable), and absolutely all units have the ability to move (Moveable). Thus, you can describe the interaction of all roles using multiple inheritance of interfaces.


Answer 7, authority 7%

May I get in)

  1. class with virtual function / functions is called – abstract

  2. abstract class can have one or more pure virtual functions

  3. if a abstract class has at least one purely virtual function, an object of such a class cannot be created, but only inherited and purely virtual functions should be redefined in the future.

  4. The

  5. interface of a class is an indication / contract with the programmer on how the programmer can use this class. those. it turns out a interface – this is all open (public ) data that a programmer can access.

essentially wrote that @VladD only in plain language

ps - for moderators, why can't I comment?

Answer 8, authority 6%

I’m new to OOP, but I dare say my own version of what’s going on.

First, programmers invented “interfaces” – as this is a very convenient thing in OOP. And then it suddenly turned out that some different classes that implement the same interface may contain almost the same pieces of code! And scattering the same pieces of code in different places in the project is no longer good. And then they invented an “abstract class”, which can perform not only the role of an interface, but also serve as an entity for highlighting common areas of code – that is, do the work that the interface would not be able to do. Those. An “abstract class” helps to avoid code duplication – after all, one of the main methods of a programmer’s work is the ability to find common sections of code and “put them out of brackets”, so to speak, which helps to reduce code duplication. Those. at the heart of all this is the fight against the complexity of development and maintenance of programs and the “abstract class” helps to solve this problem.


Answer 9, authority 3%

  1. In some languages ​​(Java …) it is possible to inherit from several interfaces, but only from the 1st class.
  2. Interface does not implement methods, but only grants access rights to use them (You can imagine an interface as a veil or a contract for access rights to something). In an abstract class, you can implement a method and override it in an inherited class, you just cannot create objects of this class.

Answer 10, authority 3%

Interface is a class that is abstract by default. In fact, an interface is needed in order to inherit from it.


Answer 11, authority 3%

An abstract class can have variables, constructors, properties, and method implementations. Interface – only method signatures.


Answer 12, authority 3%

What is an abstract class?

An abstract class is a class that is declared abstract – it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all abstract methods in its parent class.

I’ll decipher the concept of an abstract class a bit. In connection with the question why I am using an abstract class. Sometimes I just add the phrase abstract to the class, because some methods must be implemented by the user of this class and specify which methods should be abstract. Why is this necessary, however, if the user will use an abstract class, then some of his methods already have a default implementation that can be overridden, and abstract methods also overlap, only the syntax assumes the presence of the abstract modifier and the absence of a method body, thus defining only the signature. This is a property of the language and is different from other object-oriented languages. The phrase abstract does not necessarily imply abstractness or such interpretation, but only the possibility of specifying methods that must be overridden in inherited classes.

What is abstraction in programming?

In object-oriented programming, abstraction is one of three basic principles (along with encapsulation and inheritance). Through the process of abstraction, the programmer hides everything but the relevant data about the object to reduce complexity and increase efficiency.

Can an abstract class have no abstract methods?

Yes, we can have an abstract class without abstract methods, since both are independent concepts. Declaring an abstract class means that it cannot be instantiated by itself and can only be subclassed. An abstract method declaration means that the method will be defined in the subclass.

Can you create an object of an abstract class in Java?

If we could create an object of an abstract class and call its method without a body (since the method is purely virtual), then it would give an error. This is why we cannot create an object of an abstract class. In short, it is legal to have a public constructor for an abstract class. An abstract class cannot be created, but can be used if there is a corresponding implementation of this class. Abstraction itself, in contrast to inheritance, assumes the absence of implementation code. If you are using an abstract class, then you can limit yourself to declaring methods. Interfaces are abstract classes in which all methods are abstract.


Answer 13

A class is always an interface + an implementation. At least partial, as in the case of an abstract class.

An interface is a way to completely decouple interface from implementation. Those. as a completely abstract class. Serves to describe the contract of the object’s behavior when interacting with the external environment.

Interface & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Abstract Class
Relationship & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Contract & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Is a
The essence of & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Contract Description & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Template for a group of classes
When to use & nbsp; & nbsp; Always (if you don’t need state) Only when needed state
State & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; No & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; May have

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions