2.1 Abstract classes and interfaces
1) Concept
Abstract classes are special classes that cannot be instantiated, except that they have other characteristics of classes, and it is important that abstract classes include abstract methods, which are not available to ordinary classes. Abstract methods can only be declared in an abstract class and do not contain any implementations, and derived classes must overwrite them. In addition, abstract classes can derive from an abstract class that can override the base class's abstract methods or not, and if not overwritten, their derived classes must overwrite them. Interfaces are reference types, and interfaces and abstract classes implement a principle in oop that separates mutable from immutable. Abstract classes and interfaces are defined as immutable, and the variable is implemented as subclasses, and the similarities between interfaces and abstract classes have three points:
² cannot be instantiated;
² contains non-implemented method declarations;
² Derived classes must implement methods that are not implemented, abstract classes are abstract methods, and interfaces are all members (not just methods including other members);
2) Differences between abstract classes and interfaces
² class is an abstraction of an object, which can be understood as a class as an object, an abstract class called an abstraction. and an interface is just a code of conduct or a rule.
² interface Basically does not have any specific characteristics of inheritance, it only promises to be able to invoke the method
² A class can implement several interfaces at a time, but can only extend one parent class
² interfaces can contain properties, indexers, events, and those members are defined as public, in addition to methods. In addition, you cannot include any other members, such as constants, fields, constructors, destructors, static members. A class can inherit directly from multiple interfaces, but only a single class (including abstract classes) is inherited directly.
3) use of abstract classes and interfaces:
² If you expect to create multiple versions of a component, create an abstract class. Abstract classes provide an easy way to control the component version.
² If you create a feature that will be used across a wide range of heterogeneous objects, use an interface. If you want to design a small and concise function block, use the interface.
² If you want to design large functional units, use an abstract class. Abstract classes are used if you want to provide common, implemented functionality across all implementations of a component.
² Abstract classes are primarily used for closely related objects, whereas interfaces are suitable for providing common functionality for unrelated classes.
Here are some of the images I saw on the internet, really very good, hehe:
1. Aircraft will fly, birds will fly, they all inherit the same interface "Fly"; but F22 belongs to the abstract class of airplanes, the pigeons belong to the abstract class of birds.
2. Like iron doors are doors (abstract class), you want a door I can't give (can't instantiate), but I can give you a specific iron gate or wooden door (polymorphic);
And can only be the door, you can not say it is the window (single inheritance); a door may have a lock (interface) can also have a doorbell (multi-implementation). The door (abstract class) defines what you are, and the interface (lock) specifies what you can do (an interface is best to do only one thing, and you cannot ask for a lock to make a sound (interface pollution)).
2.2 Interface Polymorphism
Assuming that the Eatfood () method is not provided using the base class, instead of placing the method on the interface Iconsume, the cow and chicken classes also support this interface (cow and chicken classes must provide the execution code of the Eatfood () method), You can then access the method using the following code:
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 button1_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!";
}
Definition of Class 2.4 (P184)
There can be only one base class in C #, and if you inherit an abstract class, you must implement all the abstract members that you inherit (unless the derived class is also abstract). A class can specify multiple interfaces, such as:
public class Myclass:mybase, Imyinterface,imysecondinterface
{
}
Modifier |
Meaning |
None or internal |
Class can only be accessed in the current project |
Public |
Class can be accessed from anywhere |
Abstract or internal abstract |
The class can only be accessed in the current project, cannot be instantiated, and can inherit only |
public abstract |
Classes can be accessed anywhere, not instantiated, only inherited |
Sealed or internal sealed |
Class can only be accessed in the current project, cannot be derived, can only be instantiated |
public sealed |
Classes can be accessed anywhere, cannot be derived, and can only be instantiated |
The keyword abstract and sealed cannot be used in an interface because the two modifiers are meaningless in the interface definition (the interface does not contain execution code, so it cannot be instantiated directly and must be inheritable). Interfaces can use multiple base interfaces, such as:
Public interface Imyinterface:imybaseinterface, IMyBaseInterface2
{
}
2.5 Constructor Execution order (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 executes the mybaseclass.mybaseclass (int i) constructor.
L executes 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 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)
{}
}
The Myderivedclassmyobj=new Myderivedclass (4,8) is executed in the following order:
L EXECUTE the System.Object.Object () constructor.
L EXECUTE the Mybaseclass.mybaseclass (i) constructor.
L Execute myderivedclass.myderivedclass (int i,int j) constructor.
If the Myderivedclass definition is modified as follows:
public class Myderivedclass:mybaseclass
{
Publicmyderivedclass (): This (5,6)
{}
Publicmyderivedclass (int i, int j): Base (i)
}
The Myderivedclassmyobj=new Myderivedclass () is executed in the following order:
L EXECUTE the System.Object.Object () constructor.
L EXECUTE the Mybaseclass.mybaseclass (i) constructor.
L Execute myderivedclass.myderivedclass (int i,int j) constructor.
L EXECUTE the Myderivedclass.myderivedclass () constructor.
2.6 Defining Class Members (P209)
1) member modifier
Public: Members can be used by any code scope
Private: Members can only be accessed by code in the class (this keyword is used by default if no keyword is used)
Internal: A member can only be accessed by code within the project (assembly) that defines it
Protected: Members can only be accessed by code in a class or derived class
2) Method modifiers
Static: Accessible only through class, not through object instantiation
Abstract: The method must be overridden in a non-abstract derived class (used only in abstract classes)
Virtual: Method can override
Override: Method overrides a base class method (the keyword must be used if the method is overridden)
extern: The method definition is placed elsewhere
"Example 1" fields, properties and methods
public class MyClass
{
You can only declare or assign values in a constructor using the ReadOnly decoration
Publicreadonly Stringname;
Private Intintval;
The accessor property of property Val is protect so it cannot be used directly in main, but can be used in its derived class
Publicint Val
{
Protectedget
{
returnintval+1;
}
You cannot set permissions on two accessors at the same time
Set
{
if (value >= 0 && value <= 10)
Intval = value;
Else
Throw an exception with throw
Throw (New ArgumentOutOfRangeException ("Val", Value, "Val must be 0~10"));
}
}
The ToString method of the object class is overridden, 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;
constructor to call the base class using the base keyword in the constructor function
PublicMyClass2 (): Base ("MyClass2") {}
Because the get accessor modifier for the Val attribute of the base class is protected, it can only be accessed in the class or derived class code
Publicint Val
{
Get and set accessors for the Val attribute in the base class can be directly used in derived class code
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 <= one; 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 and non-static fields can be invoked when instantiated, only static and static fields are called when the class is called
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 constructors to assign a value to a 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, output DoSomething1 in base classes
C0=C2;
C0. DoSomething2 (); Executes the code of the inheriting class, output DoSomething2 in DerivedClass2
}
}
Class BaseClass
{
Internalvoid DoSomething1 ()
{
Console.WriteLine ("DoSomething1 in Base Class");
}
Use virtual decoration to indicate that a method can be overridden
Virtualinternal VoidDoSomething2 ()
{
Console.WriteLine ("DoSomething2 in Base Class");
}
}
Class Derivedclass1:baseclass
{
Newinternal voidDoSomething1 ()
{
Console.WriteLine ("DoSomething1 in DerivedClass1");
}
}
Class Derivedclass2:baseclass
{
Override overrides base class code
Internaloverride VoidDoSomething2 ()
{
Console.WriteLine ("DoSomething2 in DerivedClass2");
}
}
"C # Learning Notes" Ii. object-oriented programming