标签:
案例:
主要有Vehicle.cs Airplane.cs Car.cs 3个类。
Car和Airplane都继承与Vehicle类。Vehicle中Drive为虚方法,可在子类中重写,父类引用子类对象,并在car中重写了Drive方法。
1 class Vehicle 2 { 3 public void StartEngine(string noiseToMakeWhenStaring) 4 { 5 Console.WriteLine("starting engine:{0}",noiseToMakeWhenStaring); 6 } 7 8 public void StopEngine(string noiseToMakeWhenStopping) 9 { 10 Console.WriteLine("stopping engine:{0}",noiseToMakeWhenStopping); 11 } 12 13 public virtual void Drive() 14 { 15 Console.WriteLine("Default Drive method"); 16 } 17 }
1 class Airplane :Vehicle 2 { 3 public void Takeoff(){ 4 Console.WriteLine("take off"); 5 } 6 public void Land() 7 { 8 Console.WriteLine("land"); 9 } 10 }
1 class Car:Vehicle 2 { 3 public void SpeedUp() 4 { 5 Console.WriteLine("SpeedUp"); 6 } 7 8 public void SpeedDown() 9 { 10 Console.WriteLine("SpeedDown"); 11 } 12 13 public override void Drive()//重写父类Drive中的方法 14 { 15 Console.WriteLine("Motoring"); 16 } 17 }
Program.cs
1 using System; 2 3 namespace Vehicles 4 { 5 class Program 6 { 7 static void DoWork() 8 { 9 Console.WriteLine("Journey by airplane:"); 10 Airplane myplane = new Airplane(); 11 myplane.StartEngine("Contact"); 12 myplane.Takeoff(); 13 myplane.Drive(); 14 myplane.Land(); 15 myplane.StopEngine("whirr"); 16 17 Console.WriteLine("\nJourney by car"); 18 Car mycar = new Car(); 19 mycar.StartEngine("gogo"); 20 mycar.SpeedUp(); 21 mycar.Drive(); 22 mycar.SpeedDown(); 23 mycar.StopEngine("stop"); 24 25 Console.WriteLine("\nTest"); 26 Vehicle v = mycar;//父类引用子类对象; 27 v.Drive(); //运行为子类中重写的方法 28 v = myplane; 29 v.Drive(); 30 } 31 32 static void Main() 33 { 34 try 35 { 36 DoWork(); 37 } 38 catch (Exception ex) 39 { 40 Console.WriteLine("Exception: {0}", ex.Message); 41 } 42 Console.ReadKey(); 43 } 44 } 45 }
注意:
在program中父类可以引用子类对象复制,类的赋值的原则是,子类型可以赋值给父类型,反之需要进行强制转换。在子类中是用override可以重构父类的方法,代码执行过程中,会引用子类中重构的父类方法。
标签:
原文地址:http://www.cnblogs.com/SeekHit/p/4901573.html