Interface or abstract class?

For my new Pet-Project, I have a design issue that has already been resolved, but I also need other opinions.

I have two classes (simplified):

class MyObject { string name {get;set;} enum relation {get;set;} int value {get;set;} } class MyObjectGroup { string name {get;set;} enum relation {get;set;} int value {get;set;} List<MyObject> myobjects {get;set;} } 

Later in the project, MyObjectGroup and MyObject should be used the same way. For this, I could go in two ways:

  • Create Interface: IObject
  • Create an abstract class: ObjectBase

I decided to follow the path of the interface that I should not write ObjectBase every time later in the code, but IObject just for convenience - but what are the other positive effects for this path?

And secondly, how about adding IXmlSerializable to the whole story? IXmlSerializable interface inherit from IXmlSerializable or does it have more positive results for implementing IXmlSerializable in an abstract base class?

+9
c # interface theory abstract
Jul 22 '09 at 13:40
source share
15 answers

Generally speaking, the approach I use in such a situation is to have both an interface and an abstract class. Interfaces define, well, an interface. An abstract class is just a helper.

You really are not mistaken in this approach. Interfaces give you the flexibility to change your implementation. Abstract classes give you boilerplate and helper code that you do not force to use, which you would otherwise if your methods were explicitly defined in terms of the abstract class.

+16
Jul 22 '09 at 13:45
source share
— -

These are some of the differences between interfaces and abstract classes.

1A. A class can inherit (implement) one or more interfaces. Thus, in C #, interfaces are used to achieve multiple inheritance.

1B. A class can inherit only one abstract class.

2A. The interface cannot provide any code, but only a signature.

2B. An abstract class can provide full default code and / or only details that need to be redefined.

3A. An interface cannot have access modifiers for subsystems, functions, properties, etc. everything is considered publicly available.

3B. An abstract class may contain access modifiers for subsets, functions, properties.

4A. Interfaces are used to determine the peripheral capabilities of a class. E.g. A Ship and a Car can implement the IMovable interface.

4B. An abstract class defines the identifier of the core of the class and there it is used for objects.

5A. If different implementations only share method signatures, then it is better to use interfaces.

5B. If different implementations have the same look and use a common behavior or status, then it is better to use an abstract class.

6A. If we add a new method to the interface, we must keep track of all the implementations of the interface and determine the implementation for the new method.

6B. . If we add a new method to an abstract class, then we have the opportunity to provide a default implementation, and therefore all existing code can work properly.

7A. Fields cannot be defined in the interface.

7B. An abstract class can have fields and constants.

8A. An interface cannot have a constructor.

8B. In an abstract class, default constructors can be implemented.

9A. An interface can only inherit from other interfaces.

9B. An abstract class can inherit from interfaces, an abstract class, or even a class.

+9
May 07 '14 at 10:35
source share

The interface will be my default until there is a reason to use the base class, as it makes fewer decisions for us.

I would not involve IXmlSerializable if I hadn't; This is a dirty, tricky interface that often causes burning.

What are your serialization requirements? There may be better options ... however, for many serializers, the base class will be simpler than the interface. For example, for an XmlSerializer you could:

 [XmlInclude(typeof(MyObject))] // : ObjectBase [XmlInclude(typeof(MyObjectGroup))] // : ObjectBase public abstract class ObjectBase { /* */ } 

(the exact approach depends on the serializer)

+7
Jul 22 '09 at 13:45
source share

As a rule, you should consider interfaces as contracts, which some types implement and abstract classes as nodes in the inheritance hierarchy, which themselves do not exist (i.e. there is a “is” relationship between the derived class and the base abstract class), however, on in practice, you may need to use interfaces in other cases, for example, when you need multiple inheritances.

For example, IXmlSerializable in itself is not an "entity." It defines a contract that an enterprise can implement. Interfaces live outside the inheritance hierarchy.

+5
Jul 22 '09 at 13:45
source share

The interface will allow you to define the “contract” that the object should execute, providing the properties and methods described by the interface. You can refer to objects by variables such as an interface, which can cause some confusion as to what exactly is being offered.

The base class offers the opportunity to build an inheritance tree, where more complex classes (of a general type) are built on the basis of simpler base classes. The classic and annoying example in OO is usually the base class "Shape" and which is inherited by a triangle, square, etc.

The main thing is that with the interface you need to provide the entire contract to each class that implements it, with the inheritance tree (base classes) you only change / add properties and methods that are unique to the child class, common properties and methods remain in the base class.

In the above example, I would have an object "MyObjectGroup" inheriting the base class "MyObject", and nothing comes out of the interface that I can see.

+4
Jul 22 '09 at 13:50
source share

When designing classes in architecture, there are two things.

  • The behavior of the object.
  • implementation of objects.

If an object has more than one implementation, then separating the behavior of the object from its implementation is one of the keys for convenience and decoupling. Separation can be achieved either by an abstract class or by an interface, but which one is better? Let's look at an example.

Let's look at a development scenario in which things (query, class model, etc.) change very often, and you need to deliver certain versions of applications.

Initial statement of the problem : you need to create a class "Train" for the Indian railway, which has the behavior of maxSpeed ​​in 1970.

1. Business modeling with an abstract class

V 0.0 (initial problem) Initial statement of the problem: you need to create the Train class for the Indian railway, which has maxSpeed ​​behavior in 1970.

 public abstract class Train { public int maxSpeed(); } 

V 1.0 (Modified Problem 1) Modified Statement of the Problem: You need to create a Diesel Train class for the Indian Railways, which had maxSpeed ​​behavior in 1975.

 public abstract class DieselTrain extends train { public int maxFuelCapacity (); } 

V 2.0 (change 2 problem ) chanded problem: you need to create the ElectricalTrain class for the Indian Railway, which has the behavior maxSpeed, maxVoltage in 1980.

 public abstract class ElectricalTrain extends train { public int maxvoltage (); } 

V 3.0 (issue with change 3)

chanded problem statement: you need to create a HybridTrain class (uses both a diesel and an electric car) for the Indian railway, which has the behavior maxSpeed, maxVoltage, maxVoltage in 1985.

 public abstract class HybridTrain extends ElectricalTrain , DisealTrain { { Not possible in java } } {here Business modeling with abstract class fails} 

2. Business modeling with an interface

Just change the word abstract to interface and ...... your business modeling with an interface will succeed.

http://javaqna.wordpress.com/2008/08/24/why-the-use-on-interfaces-instead-of-abstract-classes-is-encouraged-in-java-programming/

+3
Feb 23 '11 at 18:14
source share

Interface: If your child classes need to implement a specific group of methods / functionality, but each of the child classes can provide its own implementation, then use interfaces.

For example, if you implement a class hierarchy for vehicles, implement an interface called Vehicle, with properties such as Color MaxSpeed, etc., and methods such as Drive (). All child classes, such as Car Scooter AirPlane SolarCar, etc., must be retrieved from this base interface, but must provide a separate implementation of the methods and properties set by Vehicle.

-> If you want your child classes to implement several unrelated functions in interfaces with short multiple inheritance, use

For example, if you are introducing the SpaceShip class, which must have functionality from a vehicle, as well as from UFOs, then make both vehicles and UFOs as interfaces, and then create a SpaceShip class that implements both Vehicle and UFO.

Abstract classes:

-> If you have a requirement that your base class provides a default implementation of certain methods, while other methods must be open for overriding by child classes, use abstract classes.

For example, again take the Vehicle class example above. If we want all the classes received from Vehicle to use the Drive () method in a fixed way, while other methods can be overridden by child classes. In this scenario, we will implement the Vehicle class as an abstract class with a Drive implementation, leaving the other methods / properties abstract so that they can be overridden by child classes.

-> The purpose of an abstract class is to provide a general definition of a base class with which several derived classes can share.

For example, a class library can define an abstract class, which is used as a parameter for many of its functions and requires programmers using this library to provide their own implementation of the class by creating a derived class.

+2
Jun 19 '16 at 6:13
source share

You really can go with OBO. ObjectBase eliminates the need to implement common properties more than once and implements IObject for you. Wherever you use it, check out IObject so you can test using mocks later

+1
Jul 22 '09 at 13:45
source share

I would prefer to go to the base abstract class, because, theoretically (well, this is just one theory, I do not prove or say that any other is worse than this) - you should use interfaces when you want to show that some object capable of doing something (for example, IComparable - you show that everything that implements it can be compared with something else), whereas if you have two instances that just share something in common or have 1 logical parent - abstract classes should be used.
You can also use both approaches, using a base class that will implement an interface that will explicitly indicate what your class can do.

+1
Jul 22 '09 at 13:50
source share

Everyone else is equal, go with the interface. It’s easier to mock unit testing.

But in general, all I use for base classes is when there is some kind of common code that I would put in one place, and not every instance of a derived class. If this is for something similar to what you are describing, the way they are used is the same, but their basic mechanics are different, the interface seems more appropriate.

+1
Jul 22 '09 at 14:23
source share

I use abstract classes in my projects, but in future projects I will use interfaces. The advantage of "multiple inheritance" is extremely useful. The ability to always offer a completely new implementation of a class, both in code and for testing purposes, is always welcome. Finally, if in the future you want to be able to customize your code by external developers, you do not need to give them your real code - they can just use the interfaces ...

0
Jul 22. '09 at 13:44
source share

If you have a function in the class, you should use the abstact class instead of an interface. In general, an interface is used on behalf of a type.

0
Jul 22 '09 at 13:53
source share

Please note that you cannot redefine operators in interfaces. This is the only real problem with them, as far as I know.

0
Jul 22 '09 at 13:56
source share

The choice of interfaces and abstract classes is not a proposal. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are great candidates within application frameworks.

Abstract classes allow you to define some behaviors; they force your subclasses to provide others. For example, if you have an application infrastructure, an abstract class can provide default services, such as event and message handling. These services allow your application to connect to the application infrastructure. However, there are some application features that only your application can run. Such features may include startup and shutdown tasks, which are often application-specific. Therefore, instead of trying to define this behavior, an abstract base class can declare abstract methods of stopping and starting. The base class knows that it needs these methods, but the abstract class allows your class to recognize that it does not know how to perform these actions; he only knows that he must initiate action. When it's time to start, an abstract class can call the start method. When the base class calls this method, Java calls the method defined by the child class.

Many developers forget that the class that defines the abstract method can also call this method. Abstract classes are a great way to create planned inheritance hierarchies. They are also a good choice for nonleaf classes in class hierarchies.

0
Dec 20 '13 at 18:05
source share

A definition of an abstract class can describe code and state, and classes that are derived from them may not be inferred from other classes at the same time. This is a technical difference.

Therefore, from the point of view of use and philosophy, the difference is that when you create an abstract class, you restrict any other functionality that the objects of this class can implement and provide these objects with some basic functions that are common to any such object (which is also a kind of restriction), and when setting up the interface, you do not set restrictions for other functions and do not make any provisions of the real code for this functionality that you have in mind. Use abstract classes when you learn everything that objects of this class should do in the interest of their users. Use interfaces when objects can also do something else that you can't even guess about.

0
Mar 30 '16 at 13:47
source share



All Articles