Class (3)-Inheritance and polymorphism

Source: Internet
Author: User

Inheritance is used to depict is-a relationships in real situations where something belongs to a certain category. C # does not support multiple inheritance, but multiple inheritance can be implemented through interfaces. By inheritance, subclasses can extend the contents of a parent class.

Polymorphism refers to the difference between types, the same request (the same method) can make a different corresponding.

The most important way to achieve polymorphism in C # is through interfaces. An interface may include any number of virtual or abstract methods, at which point the class that inherits (implements) the interface must give its own implementation (by overriding the virtual or abstract method). For example, the base class has a virtual method speak, which is not implemented, at which point all derived classes provide their own implementation, and then, for any derived class, speak corresponds to different code. We simply call X.speak () in the process, and the compiler automatically finds and executes different implementations based on the type of object x called, which is polymorphic.

Polymorphism can also be implemented by means of a subclass-replicated parent class.

overloading, overriding, and hiding

Overloading: Occurs within the same scope (for example, inside a class) and defines a series of methods with the same name, but the method has a different argument list. This allows you to decide which one to call by passing different parameters. A different return value type does not make an overload.

Override: Occurs when inheriting, redefining a method in a parent class in a subclass, and the method in the subclass is the same as the method of the parent class. For example: The base class method is declared as virtual (virtual method), and the override in the derived class is used to declare this method. Be aware that:

    • The flag of the overridden method must match the name and parameters of the overridden method (input and output) exactly to reach the effect of the overlay;
    • The exception that is thrown by the overridden method must be the same as the exception that is thrown by the overridden method, or its subclass;
    • The overridden method cannot be private, otherwise only a new method is defined in its subclass and is not overwritten.

Hidden: The base class method does not make a declaration (default is a non-virtual method), and in a derived class uses new to declare the hiding of this method. It hides any implementation on top of it (the parent class or ancestor Class).

Overload (heavy-duty)--Select the method to invoke according to the parameters;

Override (Override)-accesses the parent class subclass, calling the subclass's overriding method, at which point the method of the parent class must be modified with virtual or abstract or it cannot be rewritten;

New (hidden)--access to the parent class invokes the parent class's method, and the subclass invokes the method of the subclass.

When the child class and the parent class have exactly the same method name and input and do not use the OVERRIDE keyword to declare the override, which method to invoke depends on whether the caller is an instance of the parent class or an instance of the subclass . (This can cause compiler warnings)

For example:

classA { Public voidF () {Console.WriteLine ("A.F"); }    }    classb:a { Public New voidF ()//do not write this new is OK, the compiler added this new{Console.WriteLine ("B.f"); }    }    classTest {Static voidMain (string[] args) {b b=NewB ();            B.f (); A A=b;        A.F (); }    }

Output to
B.f
A.f

Virtual modifier words

Virtual methods, also known as virtual methods, can have their own implementations. This keyword is used for the parent class method that requires the quilt class to be overridden. Virtual methods can be overridden in subclasses, but overrides are not required . The inherited method of the subclass is overridden with the Override keyword declaration. This keyword and abstract opposites, the abstract method cannot have its own implementation, and must be overridden in subclasses.

abstract modifier words

The relationship between subcategories and parent category (note i) can be said to be a "is a" relationship. Suppose there is a category called a car, and another category called a truck. If the truck is a subcategory of the car that inherits the car category, we can say that the truck "is a" the car, which means the truck is one of the cars. What about abstract class? In principle, the simplest explanation is that abstract categories are categories that cannot be materialized in domain concepts . This seems to be very general, let us give a simple example. Suppose there is a category called shape, and the circle category and the square category are subcategories of the shapes category. In this example, the "shape" is obviously a concept of a drawing and cannot be materialized, so at design time we can choose to define "shape" as an abstract class.

Abstract classes can contain abstract methods, or they can have common methods. An abstract method is a method that only has a signature and is not implemented, and must be placed in an abstract class. Inheriting the subclass of the class if it is a generic class, you implement all the abstract methods of the parent class, and if it is an abstract class, you only need to implement an abstract method of at least one parent class. We do not want users to create an instance of an abstract class because it is meaningless (there is no property, and the method is empty). So, we have:

    1. An abstract class cannot establish an instance.
    2. Abstract classes cannot be sealed because it violates the principle that he is only meant to be inherited.
    3. Abstract classes are only meaningful if they are inherited by derived classes. For example, circles and squares derive shapes that have attribute radii, edge lengths, and methods to calculate perimeter, calculate area, and so on.

Interface

An interface is a special kind of abstract class that can be seen as a collection of abstract methods . So what he has in common with abstract types is that it contains several abstract members, and that interfaces are abstract types and cannot be instantiated.

The different points are:

    1. An interface can include only abstract methods and properties , and abstract types may include non-abstract methods (which can also include fields, constructors, etc.).
    2. All members of an interface are public, abstract. Therefore, the interface member does not specify an access modifier.
    3. The class that inherits the interface can only implement the method of the interface, not partial implementation. Classes that inherit abstract types can only implement the methods of some of the parent classes.
    4. Interfaces can also be inherited by interfaces (this is the same as abstract classes), at which point the sub-interface still cannot implement the parent interface's method (unlike the abstract class), and he can only provide additional methods. If the grandchild category appears, the grandchild category implements all the methods on the parent interface and the subinterface. An interface can inherit multiple interfaces.

An interface is treated as a container for implementing some kind of behavior. A class can inherit more than one interface, in this way, we not only realize the multiple inheritance, but also to customize the function for the class. For a class, as long as he inherits and implements an interface, it is considered to have implemented a function, similar to the fact that he plugged in a real-world interface. The interface is responsible for characterizing the has-a relationship, which is the function of something, rather than emphasizing the sense of belonging. This is different from the abstract class. object-oriented thinking and one of the core is called polymorphism, what is polymorphism? To put it bluntly is to treat the same things indiscriminately at a certain granularity view level. The reason to do this is because of the presence of interfaces (http://www.cnblogs.com/leoo2sk/archive/2008/04/10/1146447.html).

interfaces and abstract classes: One difference between an interface and an abstract class is that the abstract class and its subclasses should be a general and special relationship, and the interface is just a set of rules (-T2 bacteriophages) that its subclasses should implement.

For example, the well-known interface IEnumerable in C #, all classes that implement it can be enumerated by foreach, but the class that implements it has no relation to the enumeration itself. Interfaces are used to enrich the functions of classes, such as horizontal expansion, while abstract classes depict vertical "from general to special" relationships. Also, if we want more than one class to inherit from a class, it can only be done through an interface, such as having multiple classes implement functions that can be enumerated.

IEnumerable interface

The interface allows the implementation of its class for a foreach operation (iterator). Implementing this interface must provide the implementation of the method GetEnumerator. GetEnumerator returns a reference to the other interface IEnumerator. There are three methods in this interface, they really implement the iterator:

    • Movenext (), move the cursor back one
    • Current, reading the present value
    • Reset, place the cursor before the first member

We do not need to implement all of these 3 methods at times, and we can return classes that implement IEnumerator, such as System.Array.

     Public classParent { Public Static voidMain () {Garage g=NewGarage (); foreach(Car Cinchg) {Console.WriteLine (c.name);        } console.readkey (); }    }    //Car Object     Public classCar { Public stringName {Get;Set; }  PublicCar (stringN) { This. Name =N;} }    //The Garage class contains a set of car objects     Public classgarage:ienumerable { Publiccar[] Cararray =Newcar[2];  PublicGarage () {cararray[0] =NewCar ("Benz"); cararray[1] =NewCar ("Honda"); }         PublicIEnumerator GetEnumerator () {//with the power of System.Array, it has been implemented IEnumerator, so we can return this as a result            returnCararray.getenumerator (); }    }

implementing iterators with the yield keyword

After C # 2.0, the compiler provides the yield keyword, making it easier to implement enumerations. To put it simply,yield (which is generally in circulation) is the one that spits out a value every time it is consumed by his method until the cycle is over, as to how it can be decided by itself . By combining yield with a for loop, we can build a number of custom iterators, such as the following examples:

Iterators that replace traditional methods

         Public IEnumerator GetEnumerator ()        {            foreach in cararray)                 yield return c;        }

Iterator returned in reverse order

         Public IEnumerator GetEnumerator ()        {            for (int0 ; i--)                yieldreturn  cararray[i];        }

An iterator that returns only even items

         Public IEnumerator GetEnumerator ()        {            for (int0 ; i--)                if20)                     // can be understood as: meet the requirements, take it!                     yieldreturn  cararray[i];                        }

ICloneable

Implement the Clone () method in which the class can copy objects deeply. (New objects and original objects that are copied are no longer pointing to the same instance on the heap, they have separate values for each other)

IComparable and IComparer

Implement the CompareTo () method, which implements a comparison of the classes. Value types, such as integers, have already implemented the method, so we can compare the size of 2 integers.

     Public classcar:icomparable {//You can now compare two cars by comparing the names of cars.         Public stringName {Get;Set; }  PublicCar (stringN) { This. Name =N;} //implementing the CompareTo method        intIComparable.CompareTo (Objectc) {Car temp= C asCar; if(temp = =NULL)                Throw NewArgumentException ("Not a car"); Else            {                //using a string comparison, this ready-made method can                return string. Compare ( This. Name, Temp.name); }        }    }

If we need more than one baseline ordering method for a class (for example, name, price, etc.), we can create several new methods and make them implement the IComparer interface. At this point we can call the overload of the sort method of the array of the class, and its second argument can pass in any instance of an object that implements the IComparer interface as a baseline for sorting.

     Public classcar:icomparable { Public stringName {Get;Set; }  Public intPrice {Get;Set; } }     Public classNamecomparer:icomparer {intIcomparer.compare (Car O1, car O2) {//using a string comparison, this ready-made method can            return string.                    Compare (O1.name, o2.name); }    }     Public classPricecomparer:icomparer {intIcomparer.compare (Car O1, car O2) {if(O1.price > O2.price)return 1; Else if(O1.price = = O2.price)return 0; Else return-1; }    }     Public classMainClass { Public Static voidMain () {car[] MyCar=Newcar[2]; mycar[0] =NewCar {Name="Benz", Price= -            }; mycar[1] =NewCar {Name="Honda", Price= the            }; Array.Sort (MyCar,Newnamecomparer ()); Array.Sort (MyCar,Newpricecomparer ()); }    }


Class (3)-Inheritance and polymorphism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.