Polymorphic
1. Virtual method
2 Abstract class
Object-oriented Calculator case:
classProgram {Static voidMain (string[] args) { //implementing Polymorphism: Virtual methods, abstract classes, interfaces//Simple factory for simple calculator effect while(true) {Console.WriteLine ("Please enter the first number"); DoubleN1 =convert.todouble (Console.ReadLine ()); Console.WriteLine ("Please enter a second number"); DoubleN2 =convert.todouble (Console.ReadLine ()); Console.WriteLine ("Please enter operator"); stringOpera =Console.ReadLine (); Operafather Opf=Getopera (opera, N1, N2); Doubleres =Opf. GetResult (); Console.WriteLine (RES); } console.readkey (); } Public StaticOperafather Getopera (stringOpear,DoubleN1,Doublen2) {Operafather Opf=NULL; Switch(opear) { Case "+": Opf =NewAdd (N1,N2); Break; Case "-": Opf =NewSub (N1, N2); Break; Case "*": Opf =NewCheng (N1, N2); Break; Case "/": Opf =NewChu (N1, N2); Break; } returnOpf; } }
Public Abstract classOperafather { PublicOperafather (DoubleN1,Doublen2) { This. Numberone =N1; This. Numbertwo =N2; } Public DoubleNumberone {Get;Set; } Public DoubleNumbertwo {Get;Set; } Public Abstract DoubleGetResult (); }
class Add:operafather {
public Add (
double N1,
double Span style= "color: #000000;" > N2):
base
(N1, N2) {
public
override
double
GetResult () {
return
this . Numberone + this
class Sub:operafather {
public Sub (
double N1,
double Span style= "color: #000000;" > N2):
base
(N1, N2) {
public
override
double
GetResult () {
return
this . Numberone-this
class Cheng:operafather { Span style= "color: #0000ff;" >public Cheng (double Span style= "color: #000000;" > N2): base (N1, N2) { public override double GetResult () { return
this . Numberone * this
class Chu:operafather { public Chu (doubledouble n2) base(N1, N2) { } publicoverridedouble getresult () { return This This . numbertwo; } }
. NET Learning notes----2015-07-21 (C # Basic review 06, polymorphism review)