What is the difference between virtual and Abstract methods?

Asked

Viewed 3,650 times

10

In which cases should I prefer to use one type instead of the other?

1 answer

17


Both are mechanisms of polymorphism.

Virtual methods have implementation that can be superimposed by a derived class.

Abstract methods have no implementation and therefore, must have an implementation in the first concrete derived class of the hierarchy.

Virtual methods may be on abstract classes or concrete. Abstract methods can only be in abstract classes.

public abstract class Base {
    public abstract void MetodoAbstrato(string nome); //não há implementação

    public virtual void MetodoVirtual(int x) {
        //faz algo aqui
    }
}

public class Derivada : Base {
    public override void MetodoAbstrato(string nome) {
        //faz algo aqui
    }
    public override void MetodoVirtual(int x) {
        //faz algo aqui
    }
}

I put in the Github for future reference.

Interfaces only have abstract methods. So they don’t even need to modify virtual or abstract.

See more about using virtual.

  • "must have an implementation in the derived class." would only modify this part to have an implementation in the derived class that is not abstract.

  • @Leonardoxavier good, edited, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.