资源描述:
《24李后浪实验二 类与对象》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验二类与对象实验课程名:Java程序设计专业班级:12网工2班学号:201240420224姓名:李后浪实验时间:2014.4.21-5.2实验地点:K4-307指导教师:冯珊一、实验目的和要求①使用类来封装对象的属性和功能;②掌握类变量与实例变量,以及类方法与实例方法的区别;③掌握使用package和import语句。④巩固以下概念:子类的继承性、子类对象的创建过程、成员变量的继承与隐藏方法的继承与重写二、实验内容 任务1三角形、梯形和圆形的类封装²实验要求:编写一个Java应用程序,该程序中有3个类:Trangle、Leder和Ci
2、rcle,分别用来刻画“三角形”、“梯形”和“圆形”。具体要求如下:a)Trangle类具有类型为double的三个边,以及周长、面积属性,Trangle类具有返回周长、面积以及修改三个边的功能。另外,Trangle类还具有一个boolean型的属性,该属性用来判断三个属能否构成一个三角形。b)Lader类具有类型double的上底、下底、高、面积属性,具有返回面积的功能。c)Circle类具有类型为double的半径、周长和面积属性,具有返回周长、面积的功能。1、源代码:classTrangle{doublesideA,sideB,si
3、deC,area,length;booleanboo;publicTrangle(doublea,doubleb,doublec){sideA=a;sideB=b;sideC=c;//参数a,b,c分别赋值给sideA,sideB,sideCif(a+b>c&&b+c>a&&a+c>b)//a,b,c构成三角形的条件表达式{boo=true;//给boo赋值。}else{boo=false;//给boo赋值。}}doublegetLength(){returnsideA+sideB+sideC;//方法体,要求计算出length的值并返回
4、}publicdoublegetArea(){if(boo){doublep=(sideA+sideB+sideC)/2.0;area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));returnarea;}else{System.out.println("不是一个三角形,不能计算面积");return0;}}publicvoidsetABC(doublea,doubleb,doublec){sideA=a;sideB=b;sideC=c;//参数a,b,c分别赋值给sideA,sideB,sideC
5、if(a+b>c&&b+c>a&&a+c>b)//a,b,c构成三角形的条件表达式{boo=true;//给boo赋值。}else{boo=false;//给boo赋值。}}}classLader{doubleabove,bottom,height,area;Lader(doublea,doubleb,doubleh){above=a;bottom=b;height=h;//方法体,将参数a,b,c分别赋值给above,bottom,height}doublegetArea(){return(above+bottom)*height/2;
6、//方法体,,要求计算出area返回}}classCircle{doubleradius,area;Circle(doubler){radius=r;//方法体}doublegetArea(){returnradius*radius*Math.PI;//方法体,要求计算出area返回}doublegetLength(){return2*Math.PI*radius;//getArea方法体的代码,要求计算出length返回}voidsetRadius(doublenewRadius){radius=newRadius;}doubleget
7、Radius(){returnradius;}}publicclassAreaAndLength{publicstaticvoidmain(Stringargs[]){doublelength,area;Circlecircle=null;Trangletrangle;Laderlader;circle=newCircle(2);//创建对象circletrangle=newTrangle(3,4,5);//创建对象trangle。lader=newLader(2,3,4);//创建对象laderlength=circle.getLeng
8、th();//circle调用方法返回周长并赋值给lengthSystem.out.println("圆的周长:"+length);area=circle.getArea();//circle