实验3类与对象

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

(1)编写3个基本类:Triangle,Ladder和Circle,分别用来刻画“三角形”、“梯形”和“圆形”类;1个主类:Compute,负责计算每个形状的面积或周长。具体要求:定义3个变量:边长;和1个求周长的方法。定义3个变量:上底,下底和高;定义1个求面积的方法。定义1个变量:半径;定义2个方法:求面积、求周长。个基本类都要定义相应的构造方法,对变量进行初始化。packagetest3;classTriangle{doublea,b,c;publicTriangle(){}publicTriangle(doublea,doubleb,doublec){this.a=a;this.b=b;this.c=c;}publicdoubleC(){returna+b+c;}}classLadder{doubleup,down,height;publicLadder(){}publicLadder(doubleup,doubledown,doubleheight){this.up=up;this.down=down;this.height=height;}publicdoubleArea(){return(up+down)*height/2;}}classCircle{doubleradius;publicCircle(){}publicCircle(doubleradius){this.radius=radius;}publicdoubleArea(){returnMath.PI*radius*radius;}publicdoubleC(){returnMath.PI*radius*2.;}}publicclasstest3_a{publicstaticvoidmain(String[]args){Circlecc=newCircle(3);System.out.println(cc.Area());System.out.println(cc.C());Ladderld=newLadder(1,2,3);System.out.println(ld.Area());Triangletr=newTriangle(1,2,3);System.out.println(tr.C());}}(2)编写一个账户类Account,它包括:一个名为id的int型账号码属性,一个名为balance的double型的账号余额属性,定义一个类型为java.util.Date的属性dateCreated,用于记录账号的创建日期。同时,定义无参的构造函数,一个名为withDraw的方法从账号提取特定数目的金额,一个名为deposit的方法向账号存入特定数目的金额。请编写测试程序,测试各个方法。packagetest3;importjava.util.Calendar;importjava.util.Date;classAccount{intid;doublebalance;DatedateCreated;publicAccount(){}publicAccount(intid,doublebalance){this.id=id;this.balance=balance;this.dateCreated=(Date)Calendar.getInstance().getTime();}publicbooleanwithDraw(doublemoney){if(this.balancemoney){this.balance-=money;returntrue;}returnfalse;}publicvoiddeposit(doublemoney){this.balance+=money;}publicdoublegetBalance(){returnthis.balance;}}packagetest3publicclasstest_b{publicstaticvoidmain(String[]args){Accountac1=newAccount(12,100.);booleanresult=ac1.withDraw(1000);if(result)System.out.println(Success);else{System.out.println(Fail);ac1.deposit(1000);System.out.println(ac1.getBalance());}}}(3)编写一个封装学生的类Student,能够描述学生的“学号”、“姓名”、“性别”、“年龄”、“平均成绩”等基本属性,及获取属性、修改属性的方法和打印学生基本信息的print()方法。要求生成两个学生对象,在构造方法中进行初始化,并打印每个学生的基本信息。packagetest3;classStudent{privateintid;privateStringname;privatecharsex;privateintage;privatedoubleaverageScore;publicdoublegetAverageScore(){returnthis.averageScore;}publicvoidsetAverageScore(doublescore){this.averageScore=score;}publicStudent(){}publicStudent(intid,Stringname,charsex,intage,doublescore){this.id=id;this.name=name;this.sex=sex;this.age=age;this.averageScore=score;}publicvoidprint(){System.out.println(id++name++sex++age++averageScore);}}publicclasstest3_c{publicstaticvoidmain(String[]args){Studentst1=newStudent(1,zhang,'f',23,90);st1.print();st1.setAverageScore(80);st1.print();}}

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功