What is the difference between virtual and abstract methods?

7

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

    
asked by anonymous 13.10.2016 / 17:34

1 answer

13

Both are mechanisms of polymorphism .

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

Abstract methods do not have implementation and therefore should have an implementation in the first derived concrete class of the hierarchy.

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

public abstract class Base {
    public abstract void MetodoAbstrato(string nome); //não há implmentaçã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
    }
}

Interfaces only have abstract methods. So you do not even need to change virtual or abstract .

See more about using virtual .

    
13.10.2016 / 17:53