资源描述:
《C#面向对象程序设计续-继承》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验三C#面向对象程序设计续-继承一、实验目的1.掌握面向对象程序设计继承与派生机制的概念;2.深入理解面向对象程序设计关于多态性的概念与特征;3.掌握泛型编程设计方法。二、实验内容(实验过程中编写的程序复制到本文件中,要求输出显示部分截图复制到本文件中,下课整理后上交)1.基于C#中继承和多态性的相关概念解决:定义一个Shape抽象类,在此基础上派生出两个抽象类TwoDimensionalShape和ThreeDimensionalShape类。TwoDimensionalShape类再派生Rectangle和Cirlce类。ThreeDimensionalShape类再派生Sphere和
2、Cube类。TwoDimensionalShape只有抽象方法Area()计算二维图形面积;ThreeDimensionalShape只有抽象方法Area()计算三维图形表面积,抽象方法Volume()计算三维图形体积。创建一个程序,用Shape引用的数组保存层次中每个具体类的对象。程序输出,描述每个数组元素所指的对象。另外,在处理数组所有图形的循环中,要确定每个图形是TwoDimensionalShape还是ThreeDimensionalShape。如果是TwoDimensionalShape则显示面积,如果是ThreeDimensionalShape,则显示表面积和体积。输出类似:图形
3、1是xxx,面积是yyy图形2是xxx,面积是yyy图形3是xxx,表面积是yyy,体积是zzz图形4是xxx,表面积是yyy,体积是zzz代码:usingSystem;namespace_127{abstractpublicclassShape{publicconstdoublePI=Math.PI;abstractpublicdoubleArea();abstractpublicdoubleVolume();}abstractpublicclassTwoDimensionalShape:Shape{protecteddoublex,y;publicTwoDimensionalShape(
4、doublex1,doubley1){x=x1;y=y1;}}publicclassRectangle:TwoDimensionalShape{publicRectangle(doublex,doubley):base(x,y){}publicoverridedoubleArea(){returnx*y;}publicoverridedoubleVolume(){return0;}}publicclassCirlce:TwoDimensionalShape{publicCirlce(doubler):base(r,0){}publicoverridedoubleArea(){returnPI
5、*x*x;}publicoverridedoubleVolume(){return0;}}abstractpublicclassThreeDimensionalShape:Shape{protecteddoublex,y,z;publicThreeDimensionalShape(doublex1,doubley1,doublez1){x=x1;y=y1;z=z1;}}publicclassSphere:ThreeDimensionalShape{publicSphere(doubler1):base(r1,0,0){}publicoverridedoubleArea(){return4*P
6、I*x*x;}publicoverridedoubleVolume(){return4*PI*x*x*x/3;}}publicclassCube:ThreeDimensionalShape{publicCube(doublea,doubleb,doublec):base(a,b,c){}publicoverridedoubleArea(){return2*x*y+2*x*z+2*y*z;}publicoverridedoubleVolume(){returnx*y*z;}}classProgram{staticvoidMain(string[]args){Shaperectangle=new
7、Rectangle(1,2);Shapecirlce=newCirlce(1);ThreeDimensionalShapesphere1=newSphere1);ThreeDimensionalShapesphere2=newSphere(1);ThreeDimensionalShapecube1=newCube(1,2,3);ThreeDimensionalShapecube2=newCube(1,2,3)