[C #] inheritance of OOP

Source: Internet
Author: User
Tags define abstract scream


Preface:

There are not many questions about how to inherit from this point. Here we only describe some basic articles I think. Hope you can give me some advice.
This section describes the inheritance of C # advanced programming and think in Java. I personally think that OOP is just an idea, so it is just a syntactic difference to understand one.

 

  • Permission restriction keyword
  • Class inheritance
    • Basic Method of class inheritance
    • Benefits of class inheritance
    • Virtual method in inheritance)
    • Abstract class
    • Disadvantages of class inheritance
    • Execute sequential
    • Class that cannot be inherited
  • Interface inheritance

 

1. Basic Writing of class inheritance:

    

 public class SuperClass : Object{} public class SubClass : SuperClass{}

We use ":" To represent the inheritance of classes, and each class can only have one parent class (this is reliable, you cannot have two personal fathers, C ++ regardless ).

Superclass inherits the object class. The object class is a top-level class. Your custom top-level class (superclass) will automatically inherit this class (I think many people say: each of your classes will inherit objects. As we have said, you can only have one biological father. Such a statement is not very rigorous. The level of tier1, tier2, and Tier3 comes down, you can directly use the methods opened by the object on the top of the page ).

  

Benefits of class inheritance:

Let's first look at some damn gentleness (class )!!!

 public class Dog    {        public string Name { get; set; }        public string Age { get; set; }        public void Run()        {            Console.WriteLine("Dog is running.");        }    }    public class Cat    {        public string Name { get; set; }        public string Age { get; set; }        public void Run()        {            Console.WriteLine("Cat is running.");        }    }
View code

  

It's okay to look at it. cat and dog have names, ages, and a running method. (When I finished writing, I nodded my head and cross-handed waist. Well, it's good. It's a silly mess)

  HoweverIf one abnormal person asks you to write all the animals aside that day, you begin to build the wheel, 1234567 ....., finally, it's coming to an end. I'm overjoyed. The abnormal guy will tell you that, sorry, it's wrong. Age is meaningless. you can remove it (Nanni ....). at this time, you need to go to 1234567 again ...., oh fuck... can't I change it only once?

All can be inherited

  

    public abstract class Animal    {        public string Name { get; set; }        public string Age { get; set; }        public void Run()        {            Console.WriteLine(string.Format("{0} is running.", Name));        }    }    public class Dog : Animal    {    }    public class Cat : Animal    {    }
View code

As shown in the code, we extract a parent class: aniaml (abstract class... Later). We can fulfill the abnormal requirement again. We just need to open up a class and inherit animal,

(Scenario recovery) Hey, age doesn't make sense. You can remove it (simple...). We just need to remove the age in animal and it will be OK.

 

Here we can see that the benefits of inheritance are not: Eliminate your repeated code to make modification more convenient.

  

Virtual method in inheritance)

Another question is raised here. If I find that the methods of my parent class cannot meet my conditions, but I don't want to reload them, can I rewrite them? Answer: Yes.

  

C # provides a virtual identifier that can be used for method rewriting (Virtual Methods in Java)

    public abstract class Animal    {        public string Name { get; set; }        public string Age { get; set; }        public virtual void Run()        {            Console.WriteLine(string.Format("{0} is running.", Name));        }    }    public class Dog : Animal    {        public override void Run()        {            Console.WriteLine("Dog is running.");        }    }    public class Cat : Animal    {    }
View code

Look at the run method in animal with virtual identifiers. The virtual method can be rewritten. In the Dog class, we use override to identify and overwrite the run method, in this way, when the cat object is instantiated, the run method that I call is overwritten.

 

Some people have doubts: if you do not write virtual and override, re-write the run method directly in cat. After instantiating Cat cat = new CAT (), call the run method. A: C # Doesn't mean virtual methods like Java. If you don't want to write virtual and override, CLR thinks this is hidden. Therefore, you need to add a new keyword to the run method of the subclass, if not added
Warning.
Public class Cat: Animal
{
Public new void run ()
{
Console. writeline ("....");
}
}
The New Keyword indicates that I want to hide the method with the same name as the parent class and the same parameter (there are several points to be discussed here, which will be proposed in the section on Polymorphism)
Abstract Method
Why is there an abstract method? Oop tells us how to create an object named animal by instantiating something in reality, this is not very strange, so we have an abstract class. Abstract classes cannot be instantiated and can only be inherited and used. Public abstract class animal, just define the abstract keyword before the class.

Abstract classes can define abstract methods, which are identified by abstract keywords. All subclasses that inherit this abstract class must implement this abstract method for an instance:
  

 public abstract class Animal    {        public string Name { get; set; }        public string Age { get; set; }        public virtual void Run()        {            Console.WriteLine(string.Format("{0} is running.", Name));        }        public abstract void Scream();    }    public class Dog : Animal    {        public override void Run()        {            Console.WriteLine("Dog is running.");        }        public override void Scream()        {            throw new NotImplementedException();        }    }    public class Cat : Animal    {        public override void Scream()        {            throw new NotImplementedException();        }    }
View code

In the abstract class of animal (we have explained why animal is defined as an abstract class), we have defined an abstract method of scream. Abstract methods do not have an implementation body. They follow ";" to end. In the dog and cat classes of subclasses, we have implemented the scream method (it cannot be left blank. As long as you use the IDE tool, an error will be reported during compilation ), we can see that the scream method of the subclass has the keyword override, so abstract is considered as a virtual method, and its usage is similar.

Note: The interface is not mentioned here. It is very common to use abstract classes and interfaces together. When it comes to interfaces, let's talk about other functions of abstract classes in detail.

  

Disadvantages of class inheritance

Inheritance brings us a lot of benefits, such as eliminating code duplication and making the layers clearer and easier to modify. However, the disadvantages are also obvious, when we inherit more layers, the entire architecture will become very bloated and unclear. Let's take a simple example. Let's say that we evolved from an orangutan, whether or not the tail is gone, but the orangutan is still there, which will lead to confusion. When we are doing the class, we should put this class of things in this class, when I was a parent class, I proposed the corresponding public things, but it was terrible to use inheritance. So here I came up with a new concept-> combination.

The concept of combination is to put an object of another class in the class. If you want to use it, assign a value. If you don't want to use it, remove it directly (father, we can't give up ).

Execute sequential

  

 public abstract class SuperClass    {        public static string StaticField = "StaticFieldInSuperClass";        private string _privateField = "_privateFieldInSuperClass";        public string publicField = "publicFieldInSuperClass";        public SuperClass()        {                  }    }    public class SubClass : SuperClass    {        public static string StaticFieldInDog = "StaticFieldInSubClass";        private string _privateField = "_privateFieldInSubClass";        public SubClass()        {        }    }
View code

Let's take a look at these two classes of superclass which have static fields, private fields, common fields and a structure. subclass has a static field and private field.

When subclass = new subclass () is instantiated, the execution is sequential as follows:

1. initialize the subclass field first.

2. Execute subclass construction, and you will find that it has a parent class, so the initialization subclass construction is paused, and the parent class (superclass) is initialized)

3. initialize fields of the parent class (superclass)

4. Execute the parent class construction

5. Return the subclass to continue initializing the subclass Structure

If you are interested, you can directly debug and check the steps.

Class that cannot be inherited

The sealed class with the keyword cannot be inherited.

    

    public sealed class ConfigHelper    {          }

Therefore, it can be considered that all the fields and methods in it contain their own sealed, because they cannot be inherited and cannot be rewritten.

2. interface inheritance

Pending... something else... released first...

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.