[C #] inheritance of OOP,

Source: Internet
Author: User
Tags define abstract scream

[C #] inheritance of OOP,


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 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...


[C Language] Is there a function that can clear keys in the cache?

Fflush (stdin)
Clear standard input Cache

# Include "stdio. h"
Main ()
{
Char a, B;
Scanf ("% c", & );
// Fflush (stdin );
Scanf ("% c", & B );
Printf ("\ n % c", a, B );
}

You can try it. If there is no fflush (stdin), if you enter a string of characters "abcd", a = 'A', B = 'B'
If fflush (stdin) exists, after entering "abcd", the program continues to wait for the input, and then enters "efdfsd". The result is a = 'A', B = 'E'

What is c/o in the address information?

C/o: care of transferred...

C/O:
Abbr. 1. = care of transferred by... (letter term );
2. = carried over [accounting] Carry forward to the next page; transfer delivery (exchange term );
3. = cash order [accounting] refers to the promissory notes, pay-as-you-go tickets, cash bills, and cash orders.

Related Article

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.