Вопрос: В чем разница между абстрактной функцией и виртуальной функцией?


В чем разница между абстрактной функцией и виртуальной функцией? В каких случаях рекомендуется использовать виртуальные или абстрактные? Какой правильный подход?


1280


источник


Ответы:


Абстрактная функция не может иметь функциональность. Вы в основном говорите, что любой дочерний класс ДОЛЖЕН предоставить свою собственную версию этого метода, однако он слишком общий, чтобы даже попытаться реализовать в родительском классе.

Виртуальная функция , в основном говорит о взгляде, вот функциональность, которая может или не может быть достаточно хороша для дочернего класса. Поэтому, если это достаточно хорошо, используйте этот метод, если нет, то переопределите меня и предоставите свою собственную функциональность.


2284



Абстрактная функция не имеет реализации и может быть объявлена ​​только в абстрактном классе. Это заставляет производный класс обеспечивать реализацию. Виртуальная функция предоставляет реализацию по умолчанию и может существовать либо в абстрактном классе, либо в неабстрактном классе. Так, например:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

242



  1. Только abstractклассы могут иметь abstractчлены.
  2. Не- abstractкласс, который наследуется от abstractкласс должен overrideего abstractчлены.
  3. abstractчлен неявно virtual,
  4. abstractчлен не может обеспечить какую-либо реализацию ( abstractназывается pure virtualна некоторых языках).

68



You must always override an abstract function.

Thus:

  • Abstract functions - when the inheritor must provide its own implementation
  • Virtual - when it is up to the inheritor to decide

49



Abstract Function:

  1. It can be declared only inside abstract class.
  2. It contains only method declaration not the implementation in abstract class.
  3. It must be overridden in derived class.

Virtual Function:

  1. It can be declared inside abstract as well as non abstract class.
  2. It contains method implementation.
  3. It may be overridden.

30



Abstract method: When a class contains an abstract method, that class must be declared as abstract. The abstract method has no implementation and thus, classes that derive from that abstract class, must provide an implementation for this abstract method.

Virtual method: A class can have a virtual method. The virtual method has an implementation. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.

When to use what: In some cases, you know that certain types should have a specific method, but, you don't know what implementation this method should have.
In such cases, you can create an interface which contains a method with this signature. However, if you have such a case, but you know that implementors of that interface will also have another common method (for which you can already provide the implementation), you can create an abstract class. This abstract class then contains the abstract method (which must be overriden), and another method which contains the 'common' logic.

A virtual method should be used if you have a class which can be used directly, but for which you want inheritors to be able to change certain behaviour, although it is not mandatory.


27



explanation: with analogies. hopefully it will help you.

Context

I work on the 21 st floor of a building. And I'm paranoid about fire. Every now and again, somewhere in the world, a fire is burning down a sky scraper. But luckily we have an instruction manual somewhere here on what to do in case of fire:

FireEscape()

  1. Don't collect belongings
  2. Walk to fire escape
  3. Walk out of building

This is basically a virtual method called FireEscape()

Virtual Method

This plan is pretty good for 99% of the circumstances. It's a basic plan which works. But there is a 1% chance that the fire escape is blocked or damaged in which case you are completely screwed and you'll become toast unless you take some drastic action. With virtual methods you can do just that: you can override the basic FireEscape() plan with your own version of the plan:

  1. Run to window
  2. Jump out the window
  3. Parachute safely to the bottom

In other words virtual methods provide a basic plan, which can be overriden if you need to. Subclasses can override the parent class' virtual method if the programmer deems it appropriate.

Abstract methods

Not all organisations are well drilled. Some organisations don't do fire drills. They don't have an overall escape policy. Every man is for himself. Management are only interested in such a policy existing.

In other words, each person is forced to develop his own FireEscape() method. One guy will walk out the fire escape. Another guy will parachute. Another guy will use rocket propulsion technology to fly away from the building. Another guy will abseil out. Management don't care how you escape, so long as you have a basic FireEscape() plan - if they don't you can be guaranteed OHS will come down on the organisation like a tonne of bricks. This is what is meant by an abstract method.

What's the difference between the two again?

Abstract method: sub classes are forced to implement their own FireEscape method. With a virtual method, you have a basic plan waiting for you, but can choose to implement your own if it's not good enough.

Now that wasn't so hard was it?


22



An abstract method is a method that must be implemented to make a concrete class. The declaration is in the abstract class (and any class with an abstract method must be an abstract class) and it must be implemented in a concrete class.

A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. If you don't override, you get the original behavior. If you do, you always get the new behavior. This opposed to not virtual methods, that can not be overridden but can hide the original method. This is done using the new modifier.

See the following example:

public class BaseClass
{
    public void SayHello()
    {
        Console.WriteLine("Hello");
    }


    public virtual void SayGoodbye()
    {
        Console.WriteLine("Goodbye");
    }

    public void HelloGoodbye()
    {
        this.SayHello();
        this.SayGoodbye();
    }
}


public class DerivedClass : BaseClass
{
    public new void SayHello()
    {
        Console.WriteLine("Hi There");
    }


    public override void SayGoodbye()
    {
        Console.WriteLine("See you later");
    }
}

When I instantiate DerivedClass and call SayHello, or SayGoodbye, I get "Hi There" and "See you later". If I call HelloGoodbye, I get "Hello" and "See you later". This is because SayGoodbye is virtual, and can be replaced by derived classes. SayHello is only hidden, so when I call that from my base class I get my original method.

Abstract methods are implicitly virtual. They define behavior that must be present, more like an interface does.


21