Interfaces, abstract classes, virtual methods, override, override relationship

1, heavy

Overload is in the same class, the same method name, a different parameter list. Different parameter list comprising: a number of different parameters and different parameter types. May not return the same data type. code show as below:

public class ClassA
{
  public void Search()
  public string Search(int a)
  public int Search(string b)
}

In other words, although they the same name, but the method is independent, there is no relationship.

2, rewriting is subclass overrides a superclass method, the parent class declares a virtual method, subclasses may choose to override or not. If you override, search method call is to call the ClassB in subclass rewritten, which is a method of ClassB. If you do not override the method call search method is to call in ClassC inherit the parent class, which is the method of ClassC. This rewrite method of non-abstract class, the method may be overridden virtual keyword must be added later in the modifier, the method also requires rewriting modifiers followed by the override keyword. code show as below:

    public class ClassA
    {
        public virtual string Search()
        {
            return "A";
        }
    }
    public class ClassB : ClassA
    {
        public override string Search()
        {
            return "B";
        }
    }
    public class ClassC : ClassA
    {
    }

3, it may also be used to implement the abstract method override. But the abstract methods must be placed in an abstract class, abstract method in the abstract class subclass inherits the abstract class must implement, non-abstract methods abstract class not enforced. Abstract methods abstract class without a subject, and an abstract class can not be instantiated, only inherited by subclasses to call. Declare an abstract class abstract and abstract methods need to add keywords after modifier, subclasses implement (rewrite) abstract method, you need to add the override keyword in the modifier. code show as below:

    public abstract class ClassA
    {
        public abstract string Search();
        public void test() { }
    }
    public class ClassB : ClassA
    {
        public override string Search()
        {
            return "B";
        }
    }

4, similar to the implementation of the interface and the abstract class, the class inherits the interface must be implemented method interface. But the difference is that the interface method does not require a modifier, not directly in the interface (methods can not have a body), no keywords. And a class can only inherit a class, but they can inherit multiple interfaces. code show as below:

    public interface ITest
    {
        string Search();
    }
    public class ClassB : ITest
    {
        public string Search()
        {
            return "";
        }
    }

Guess you like

Origin www.cnblogs.com/liangshibo/p/12197106.html