题目描述
Pow类定义了一个求幂对象的抽象概念。Pow类方法是抽象的,Pow B类和Pow C类是Pow的具体实现。(控制台应用程序)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 抽象类与抽象方法声明 { class Program { static void Main(string[] args) { Pow_B mypowB = new Pow_B(); mypowB.PowMethod(2,10); Pow_C myPowC = new Pow_C(); myPowC.PowMethod(2,10); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 抽象类与抽象方法声明 { public abstract class Pow { public abstract void PowMethod(int x, int y); } //abstract方法 没有自己的实现 //virtual方法 有自己的实现 //共同点:都可以通过override来实现对原有方法的重写 }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 抽象类与抽象方法声明 { class Pow_B:Pow { public override void PowMethod(int x, int y) { int pow = 1; for (int i = 1; i <= y; i++) { pow *= x; } Console.WriteLine("求幂的结果是"+pow); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 抽象类与抽象方法声明 { class Pow_C:Pow { public override void PowMethod(int x, int y) { Console.WriteLine("求幂的结果是"+System.Math.Pow(x, y)); } } }
***抽象方法必须在抽象类中声明
不能使用static、private或virtual修饰符
方法不能有任何可执行程序,哪怕是方法体
抽象类不能实例化,必须通过继承由派生类实现其抽象方法,因此不能new,不能sealed
如果派生类没有实现所有的抽象方法,则该派生类也必须声明为抽象类
如果一个非抽象类从抽象类中派生,则其必须通过重载来实现所有继承而来的抽象成员