"Reading notes" C # Advanced Programming fourth Chapter inheritance

Source: Internet
Author: User

(i) Types of inheritance

1. Implement inheritance and interface inheritance

In object-oriented programming, there are two distinct types of inheritance: implementation inheritance and interface inheritance.

    • Implementation inheritance: Represents a type that derives from a base type that owns all member fields and functions of that base type. In implementation inheritance, a derived type takes each function code of a base type, unless the implementation code that overrides a function is specified in the definition of a derived type. This type of inheritance is useful when you need to add functionality to an existing type, or if many of the related types share a significant set of common functionality.
    • Interface Inheritance: Indicates that a type inherits only the signature of a function and does not inherit any implementation code. This type of inheritance is best used when it is necessary to have certain features available for that type.

2. Multiple inheritance

C # does not support multi-implementation inheritance, but allows a type to derive from multiple interfaces-multiple interface inheritance. To be precise, because System.Object is a common base class, each C # class (except the object class) has a base class and can have any number of base interfaces.

3. Structure and Class

Structs do not support implementation inheritance, but interface inheritance is supported.

Defining structures and classes can be summarized as:

    • Structs are always derived from System.ValueType, and they can also derive from any number of interfaces.
    • Classes are always derived from System.Object or another class that the user chooses, and they can also derive from any number of interfaces.

(ii) Implementation of inheritance

Declares a class derived from another class with the following syntax:

Example:

The following code creates the MyBaseClass class, the MyClass class, where the MyClass class derives from the MyBaseClass class

class mybaseclass{} class myclass:mybaseclass{}

If the class (or struct) is also derived from the interface, the base class and interface in the list are separated by commas:

class Myclass:mybaseclass,iinterface1,iinterface2 {}

For structs, the syntax is as follows:

 Public struct Mystruct:iinterface1, iinterface2{}

1. Virtual method

If you declare a base class function as virtual, you can override the function in any derived class:

class mybaseclass{    publicvirtualstring  virtualmethod ()    {         return" virtual method ";    }}

In C #, a function is not virtual by default, but (outside the constructor) can be explicitly declared as virtual. At the same time, C # requires that when a derived class overrides a function in a base class, it is explicitly declared with the override keyword:

class Myclass:mybaseclass, IInterface1, iinterface2{    publicoverridestring  Virtualmethod ()    {        return" overrides the virtual method of the base class ";}    }

2. Hidden methods

If a method with the same signature is declared in both the base class and the derived class, but the method is not declared separately as virtual and override, the derived class method hides the base class method.

Example:

In the following code, the base class and the derived class have the same method, ShowName, when we need to hide the methods in the base class, we should display the keyword new, or the compiler will issue a warning. The base class method is hidden, and we cannot access the base class method through the derived class, but only through the derived class itself.

class mybaseclass{    publicvoid showname (string  name)    {        Console.WriteLine (name);}    } class Myclass:mybaseclass, IInterface1, {    publicnewvoid showname (  String  name)    {        Console.WriteLine (" derived class "+name);}    } 

In most cases, we should override the method instead of hiding the method, because hiding the method can cause a risk of invoking the wrong method on the instance of the given class.

3. Call the base class version of the function

C # has a special syntax for calling the base class version:base.<methodname> () of a method from a derived class.

Example:

The following code on the base class to print out the name of the base, and then a line of welcome words

classmybaseclass{ Public Virtual voidShowName (stringname)    {Console.WriteLine (name); }}classMyclass:mybaseclass, IInterface1, iinte{ Public Override voidShowName (stringname) {        Base.        ShowName (name); Console.WriteLine ("you are welcome to visit! "); }}

Run the above code with the following results:

4. Abstract classes and abstract functions

C # allows classes and functions to be declared abstract. Abstract classes cannot be instantiated, and abstract functions cannot be implemented directly, and must be overridden in non-abstract derived classes. If a class contains abstract functions, the class is also abstract and must be declared as an abstract class.

Example:

The following code creates an abstract class and an abstract method

Abstract class Myabstractclass {    publicabstractvoid  Firstabstractmethod ();}

5. Sealing type and Sealing method

C # allows classes and methods to be declared as sealed. For a class, this means that the class cannot be inherited, and for methods, this means that the method cannot be overridden.

Example:

Sealed class fisrtsealedclass{} class readyclass:fisrtsealedclass{}

At this point the compiler will error

Declare the method as sealed

Example:

classmybaseclass{ Public Virtual voidShowName (stringname)    {Console.WriteLine (name); }}classMyclass:mybaseclass, IInterface1, iinterface2{ Public Sealed Override voidShowName (stringname) {        Base.        ShowName (name); Console.WriteLine ("you are welcome to visit! "); }}

To use the sealed keyword on a method or property, you must first declare it as a method or property to override from the base class. If the base class is to be sealed, it is not declared as virtual.

6. Constructors for derived classes

Example:

class mybaseclass{    public  MyBaseClass () {}    public mybaseclass (int  i) {}}class  myclass:mybaseclass{    public  MyClass () {}      Public MyClass (int  i) {}    public MyClass (int i ,int  j) {}} 

If MyClass is instantiated in the following ways:

New MyClass ();

The constructor is executed in the following order:

    1. Executes the System.Object.Object () constructor;
    2. Executes the Mybaseclass.mybaseclass () constructor;
    3. Executes the Myclass.myclass () constructor.

If MyClass is instantiated in the following ways:

New MyClass (4);

The constructor is executed in the following order:

    1. Executes the System.Object.Object () constructor;
    2. Executes the Mybaseclass.mybaseclass () constructor;
    3. Executes the myclass.myclass (int i) constructor.

Finally, instantiate the MyClass using the following method:

New MyClass (48);

The constructor is executed in the following order:

    1. Executes the System.Object.Object () constructor;
    2. Executes the Mybaseclass.mybaseclass () constructor;
    3. Executes the myclass.myclass (int I,int j) constructor.

You can also use base () and this () to change the order in which constructors are executed

class mybaseclass{    public  MyBaseClass () {}    public mybaseclass (int  i) {}}class  myclass:mybaseclass{    public  MyClass () {}      Public MyClass (int  i) {}    public MyClass (int intBase  (i) {}}

At this point we instantiate the MyClass in the following way:

New MyClass (48);

This time the constructor is executed in the following order:

    1. Executes the System.Object.Object () constructor;
    2. Executes the mybaseclass.mybaseclass (int i) constructor;
    3. Executes the myclass.myclass (int I,int j) constructor.

The base keyword is specified. The net instantiation process uses a constructor with the specified parameters in the base class.

class mybaseclass{    public  MyBaseClass () {}    public mybaseclass (int  i) {}}class  myclass:mybaseclass{    public  MyClass () {}      Public MyClass (intthis5) {}    public MyClass (int  int j) {}}

At this point we instantiate the MyClass in the following way:

New MyClass (4);

This time the constructor is executed in the following order:

    1. Executes the System.Object.Object () constructor;
    2. Executes the Mybaseclass.mybaseclass () constructor;
    3. Executes the myclass.myclass (int i,int j) constructor;
    4. Executes the myclass.myclass (int i) constructor.

The This keyword keyword is specified. The net instantiation process uses a constructor with the specified parameters in the current class.

However, it is important to note that there is no infinite loop:

class myclass:mybaseclass{    Public This (1) {}    public MyClass (intThis() {}}

The above code is specified through this, resulting in an infinite loop.

Through the analysis of the above code, we can know that the call order of constructors is to call System.Object first, and then proceed from top to bottom according to the hierarchy until the class that the compiler is instantiating is reached.

The default constructor for the base class is used, regardless of the constructor (default constructor or non-default constructor) that is used on the derived class, unless explicitly specified.

(c) Modifier

modifier, which is the keyword applied to the type or member.

1. Visibility modifier

Modifier Applied to Description
Public All types or members Any code can access the item
Protected All members of type and inline type Only derived types can access the item
Internal All types or members The item can only be accessed in the assembly that contains it
Private All members of type and inline type The item can only be accessed in the type to which it belongs
protected internal All members of type and inline type The item can only be accessed in any code that contains its assembly and derived type

2. Other modifiers

Modifier Applied to Description
New Function members Members hide inherited members with the same signature
Static All Members A member does not function with a specific instance of a class
Virtual Function Members Only Members can be overridden by derived classes
Abstract Function Members Only The virtual member defines the signature of the member, but does not provide the implementation code
Override Function Members Only A member overrides an inherited virtual or abstract member
Sealed Classes, methods, and properties For classes, you cannot inherit from a sealed class. For properties and methods, a member overrides an inherited virtual member, but a member in any derived class cannot override the member. The modifier must be used with override
extern static only [DllImport] method Members are externally implemented in a different language

(iv) interface

If a class derives from an interface, declaring the class implements some functions.

Interfaces can only contain declarations for methods, properties, indexers, and events.

An interface cannot be instantiated, it can only contain the signatures of its members.

Interfaces are always common and cannot be declared as virtual or static.

Interfaces usually start with the letter I to know that this is an interface.

1. Define and implement interfaces

First we define an interface, the interface function is a speaking interface

Interface Italk {    void talk (string  str);}

Next we implement the interface through class Chinese.

class chinese:italk{    publicvoid talk (string  str)    {        Console.WriteLine (" Chinese Voice:" + str);}    }

You can also define a American to implement the interface

class American:italk {    publicvoid talk (string  str)    {        Console.WriteLine ("中文版:" + str);}    }

Through the interface of inheritance, we realize that people of different countries can speak such a function, external calls when we through the interface reference can be very convenient to call.

2. Derivation of the interface

When Italk does not meet the requirements, it is assumed that this time when a speak function needs to be added to Chinese and American, the interface can be derived to achieve

Interface ilanguage:italk{    void Speak (string  str);}

The changed interface implementation

classchinese:ilanguage{ Public voidSpeak (stringstr) {Console.WriteLine ("speech in Chinese:"+str); }     Public voidTalkstringstr) {Console.WriteLine ("Chinese Voice:"+str); }}classamerican:ilanguage{ Public voidSpeak (stringstr) {Console.WriteLine ("中文版 Speak:"+str); }     Public voidTalkstringstr) {Console.WriteLine ("中文版:"+str); }}

"Reading notes" C # Advanced Programming fourth Chapter inheritance

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.