[C # Study Notes] 2. object-oriented programming,

Source: Internet
Author: User

[C # Study Notes] 2. object-oriented programming,
2.1 abstract classes and interfaces

1) Concept

Abstract classes are special classes, but they cannot be instantiated. In addition, they have other characteristics of the class. It is important that abstract classes can include abstract methods, which are not supported by common classes. Abstract METHODS can only be declared in abstract classes and do not contain any implementations. The Derived classes must overwrite them. In addition, an abstract class can be derived from an abstract class. It can overwrite the abstract methods of the base class or overwrite them. If not, its derived class must overwrite them. The interface is of reference type. The interface and the abstract class implement a principle in oop to separate mutable from immutable. Abstract classes and interfaces are defined as immutable classes and can be implemented as subclasses. The similarities between interfaces and abstract classes are as follows:

2. It cannot be instantiated;

2. Contains the unimplemented method declaration;

2. The derived class must implement unimplemented methods. The abstract class is an abstract method, and the interface is all members (not only the methods include other members );

 

2) differences between abstract classes and interfaces

2. A class is an abstraction of an object. It can be understood as an object. An abstract class is called an abstract class. An interface is just a behavior specification or provision.

2. The interface basically does not have any specific characteristics of inheritance. It only promises the methods that can be called.

2. A class can implement several interfaces at a time, but only one parent class can be extended.

2. interfaces can contain methods, attributes, indexers, and events, and these members are defined as common. It cannot contain any other Members, such as constants, fields, constructors, destructor, and static members. A class can directly inherit multiple interfaces, but can only inherit one class (including abstract classes ).


3) Use of abstract classes and interfaces:

2. If multiple versions of a component are expected to be created, an abstract class is created. Abstract classes provide simple methods to control component versions.

2. If the created function is used across a wide range of different objects, the interface is used. If you want to design small and concise functional blocks, use interfaces.

2. If you want to design a large functional unit, use an abstract class. If you want to provide general implemented functions among all the implementations of the component, use an abstract class.

2. abstract classes are mainly used for closely related objects. interfaces are suitable for providing general functions for irrelevant classes.


The following are some of the Image metaphors I have seen on the Internet. They are really good:
1. Planes fly and birds fly. They all inherit the same interface "fly". However, F22 belongs to the aircraft abstract class and pigeon belongs to the bird abstract class.
2. As the doors of the iron door are all doors (abstract classes), you can give me a specific iron door or wooden door (polymorphism), but I can give you a specific iron door or wooden door );

It can only be a door. You cannot say it is a window (single inheritance); a door can have a lock (Interface) or a doorbell (multiple implementations ). A door (abstract class) defines what you are and an interface (LOCK) specifies what you can do (one interface is best to do only one thing, you cannot require the lock to make sound (interface pollution )).

2.2 interface Polymorphism

Assume that the base class is not used to provide the EatFood () method, but the method is put on the Interface IConsume. The Cow and Chicken classes also support this interface (the Cow and Chicken classes must provide EatFood () method Execution Code), then you can use the following code to access the method:

Cow myCow = new Cow ();

Chicken myChicken = new Chicken ();

IConsume consumeInterface;

ConsumeInterface = myConw;

ConsumeInterface. EatFood ();

ConsumeInterface = myChicken;

ConsumeInterface. EatFood;

2.3 OOP (P180) in the Window Application)

[Example 1]

Private void button#click (objectsender, System. EventArgs e)

{

(CButton) sender). Text = "Clicked !";

ButtonnewButton = new Button ();

NewButton. Text = "NewButton !";

NewButton. Click + = newEventHandler (newButton_Click );

Controls. Add (newButton );

}

Private void newButton_Click (objectsender, System. EventArgs e)

{

(Button) sender). Text = "Clicked !";

}

2.4 class definition (P184)

C # can only have one base class. If an abstract class is inherited, all the abstract members inherited must be implemented (unless the derived class is also abstract ). A class can specify multiple interfaces, such:

Public class MyClass: MyBase, IMyInterface, IMySecondInterface

{

}

Modifier

Description

None or internal

Class can only be accessed in the current project

Public

Class can be accessed anywhere

Abstract or internal abstract

Class can only be accessed in the current project, cannot be instantiated, can only inherit

Public abstract

Class can be accessed anywhere. It cannot be instantiated and can only be inherited.

Sealed or internal sealed

Class can only be accessed in the current project, cannot be derived, can only be instantiated

Public sealed

Class can be accessed anywhere, cannot be derived, can only be instantiated

 

Abstract and sealed keywords cannot be used in the interface, because these two modifiers are meaningless in the interface definition (the interface does not contain Execution Code, so they cannot be directly instantiated, and must be inherited ). The interface can use multiple basic interfaces, such:

Public interface IMyInterface: IMyBaseInterface, IMyBaseInterface2

{

}

2.5 constructor execution sequence (P192)

Public class MyBaseClass

{

PublicMyBaseClass (){}

PublicMyBaseClass (int I ){}

}

Public class MyDerivedClass: MyBaseClass

{

PublicMyDerivedClass (){}

PublicMyDerivedClass (int I ){}

Public MyDerivedClass (inti, int j ){}

}

 

MyDerivedClass myObj = new MyDerivedClass ();

L execute the System. Object. Object () constructor.

L execute the MyBaseClass. MyBaseClass () constructor.

L execute the MyDerivedClass. MyDerivedClass () constructor.

 

MyDerivedClass myObj = new MyDerivedClass (4 );

L execute the System. Object. Object () constructor.

L execute the MyBaseClass. MyBaseClass (int I) constructor.

L execute the MyDerivedClass. MyDerivedClass (int I) constructor.

 

MyDerivedClass myObj = newMyDerivedClass (4, 8 );

L execute the System. Object. Object () constructor.

L execute the MyBaseClass. MyBaseClass () constructor.

L execute the MyDerivedClass. MyDerivedClass (int I, int j) constructor.

 

If the definition of MyDerivedClass is modified as follows:

Public class MyDerivedClass: MyBaseClass

{

....

PublicMyDerivedClass (int I, int j): base (I)

{}

}

MyDerivedClassmyObj = new MyDerivedClass (); the execution sequence is as follows:

L execute the System. Object. Object () constructor.

L execute the MyBaseClass. MyBaseClass (I) constructor.

L execute the MyDerivedClass. MyDerivedClass (int I, int j) constructor.

 

If MyDerivedClass is defined as follows:

Public class MyDerivedClass: MyBaseClass

{

PublicMyDerivedClass (): this (5, 6)

{}

PublicMyDerivedClass (int I, int j): base (I)

}

Then, the execution order of MyDerivedClassmyObj = new MyDerivedClass (); is as follows:

L execute the System. Object. Object () constructor.

L execute the MyBaseClass. MyBaseClass (I) constructor.

L execute the MyDerivedClass. MyDerivedClass (int I, int j) constructor.

L execute the MyDerivedClass. MyDerivedClass () constructor.

2.6 define class members (P209)

1) member Modifier

Public: Members can be within any code range.

Private: members can only be accessed by code in the class (if no keyword is used, this keyword is used by default)

Internal: members can only be accessed by code inside the project (assembly) that defines them.

Protected: members can only be accessed by code in the class or derived class.

 

2) method Modifier

Static: It can only be accessed through classes and cannot be accessed through Object Instantiation.

Abstract: methods must be rewritten in a non-abstract derived class (only used in abstract classes)

Virtual: The method can be rewritten.

Override: The method overrides a base class method (this keyword is required if the method is overwritten)

Extern: place the method definition elsewhere.

 

[Example 1] fields, attributes, and methods

Public class MyClass

{

// Use readonly to modify the value. The value can only be declared or assigned to the constructor.

Publicreadonly stringName;

Private intintVal;

// The accessor attribute of attribute Val is protect, so it cannot be used directly in main, but can be used in its derived class

Publicint Val

{

Protectedget

{

ReturnintVal + 1;

}

// The permissions of the two accessors cannot be set at the same time.

Set

{

If (value> = 0 & value <= 10)

IntVal = value;

Else

// Throw an exception

Throw (new ArgumentOutOfRangeException ("Val", value, "Val must be 0 ~ 10 "));

}

}

// Override the ToString method of the Object class, so use the override Modifier

Publicoverride stringToString ()

{

Return "Name:" + Name + "\ nVal:" + Val;

}

// Use the this keyword to call its own MyClass (string newName) constructor

PrivateMyClass (): this ("DefaultName "){}

PublicMyClass (string newName)

{

Name = newName;

IntVal = 0;

}

}

Public class MyClass2: MyClass

{

Internalint myVal;

// Use the base keyword in the constructor to call the constructor of the base class.

PublicMyClass2 (): base ("MyClass2 "){}

// Because the get accesser modifier of the Val attribute of the base class is protected, it can only be accessed in the code of the class or derived class

Publicint Val

{

// The get and set accessors of the Val attribute in the base class can be directly used in the code of the derived class.

Get {return base. Val ;}

Set {base. Val = value ;}

}

}

 

Class Program

{

Static void Main (string [] args)

{

MyClass2 obj2 = new MyClass2 ();

Console. WriteLine (obj2.ToString ());

Obj2.myVal = 20;

Console. WriteLine ("obj2.myVal = {0}", obj2.myVal );

For (int I = 0; I <= 11; I ++)

{

Obj2.Val = I;

Console. WriteLine ("intVal = {0}", obj2.Val );

}

Console. ReadKey ();

}

}

 

[Example 2]] Static fields and static methods in the class (Ch09Ex03)

ClassProgram

{

Static voidMain (string [] args)

{

// Only non-static functions and non-static fields can be called during instantiation. Only static functions and static fields can be called during class calling.

MyExternalClassmyClass = new MyExternalClass (2 );

MyClass. ShowIntVal ();

MyExternalClass. strName = "My Static Name ";

MyExternalClass. ShowName ();

Console. ReadKey ();

}

}

Public class MyExternalClass

{

Private intmyIntVal;

Publicstatic stringstrName;

Publicstatic voidShowName ()

{

Console. WriteLine (strName );

}

// Use the constructor to assign values to the private variable myIntVal

Public MyExternalClass (int nVal)

{

MyIntVal = nVal;

}

Publicvoid ShowIntVal ()

{

Console. WriteLine ("MyIntVal = {0}", myIntVal );

}

}

2.7 hiding base class methods (P219)

Class Program

{

Staticvoid Main (string [] args)

{

DerivedClass1C1 = new DerivedClass1 ();

DerivedClass2C2 = new DerivedClass2 ();

C1.DoSomething1 ();

C2.DoSomething2 ();

 

BaseClassC0;

C0 = C1;

C0.DoSomething1 (); // executes the code of the Base Class and outputs DoSomething1 In Base Class.

C0 = C2;

C0.DoSomething2 (); // execute the inheritance class code and output DoSomething2 In DerivedClass2

}

}

Class BaseClass

{

Internalvoid DoSomething1 ()

{

Console. WriteLine ("DoSomething1 In Base Class ");

}

// Use virtual modifier to indicate that the method can be overwritten

Virtualinternal voidDoSomething2 ()

{

Console. WriteLine ("DoSomething2 In Base Class ");

}

}

Class DerivedClass1: BaseClass

{

Newinternal voidDoSomething1 ()

{

Console. WriteLine ("DoSomething1 In DerivedClass1 ");

}

}

Class DerivedClass2: BaseClass

{

// Override will rewrite the base class code

Internaloverride voidDoSomething2 ()

{

Console. WriteLine ("DoSomething2 In DerivedClass2 ");

}

}

 

 

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.