实验五-继承与接口_第1页
实验五-继承与接口_第2页
实验五-继承与接口_第3页
实验五-继承与接口_第4页
实验五-继承与接口_第5页
免费预览已结束,剩余30页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、实验五 继承与接口1. 实验目的1、掌握类的继承细节内容,包括子类的继承、子类对象创建、成员变量的继承与隐藏、方法的继承与重写2、掌握重写的目的以及怎样使用super 关键字3、掌握上转型对象与接口回调技术4、掌握类怎样实现接口,及面向接口的编程思想2. 实验内容1、根据附录里的源代码,按照注释要求,完成代码填空,使程序能够运行得出结果。1)实验 1 中国人与美国人package boy;public class People protected double weight , height ;public void speakHello()System. out .println( &quo

2、t;yayayaya" ); public void averageHeight() height =173;System. out .println( "average height:" +height );public void averageWeight()weight =70;System. out .println( "average weight:" +weight ); package boy;public class ChinaPeople extends Peoplepublic void speakHello() Syste

3、m. out .println( " 你好 " );public void averageHeight()height =168.78;System. out .println( " 中国人的平均身高:" +height +" 厘米 " );public void averageWeight() weight =65;System. out .println( " 中国人的平均体重:" +weight +" 公斤 " );/【代码1】/重写public void averageWeight()方

4、法,输出:"中国人的平均体重:65公斤"public void chinaGongfu()System. out .println( "坐如钟,站如松,睡如弓");package boy;public class AmericanPeople extends Peoplepublic void speakHello() System. out .println( "How do you do" );public void averageHeight() System. out .println( "American'

5、s average height:176cm");/ 【代码 2】/ 重写 public void speakHello()方法,输出:"How do you do"/ 【代码 3】/ 重写 public void averageHeight()方法,输出:"American's averageheight:176cm"public void averageWeight()weight =75;System. out .println( "American's average weight:"+weight

6、+"kg");public void americanBoxing()System. out .println( "直拳、钩拳、组合拳 ");package boy;public class BeijingPeople extends ChinaPeople public void averageHeight() System. out .println( "北京人的平均身高 :172.5 厘米"); public void averageWeight() System. out .println( "北京人的平均体重 :7

7、0 公斤"); /【代码4】/重写public void averageHeight() 方法,输出:"北京人的平均身高:172.5 厘米" /【代码5】/重写public void averageWeight()方法,输出:"北京人的平均体重:70公斤”public void beijingOpera()System. out .println( "花脸、青衣、花旦和老生");package boy;public class Example public static void main(String口 args ) ChinaPe

8、ople chinaPeople = new ChinaPeople(); AmericanPeople americanPeople = new AmericanPeople(); BeijingPeople beijingPeople = new BeijingPeople(); chinaPeople .speakHello();americanPeople .speakHello();beijingPeople .speakHello();chinaPeople .averageHeight(); americanPeople .averageHeight(); beijingPeop

9、le .averageHeight(); chinaPeople .averageWeight(); americanPeople .averageWeight(); beijingPeople .averageWeight(); chinaPeople .chinaGongfu(); americanPeople .americanBoxing(); beijingPeople.beijingOpera();beijingPeople.chinaGongfu();你好How do you do你好中国人的平均身高:168.78 厘米American's average height:

10、176cm 北京人的平均身高:172.5 厘米 中国人的平均体重:65.0 公斤American's average weight:75.0kg 北京人的平均体重:70公斤 坐如钟,站如松,睡如弓 直拳、钩拳、组合拳 花脸、青衣、花旦和老生 坐如钟,站如松,睡如弓2)实验2银行与利息package boy;public class Bank int savedMoney ;int year ;double interest ;public double computerInterest()interest =year * interestRate * savedMoney ; retu

11、rn interest ;public void setInterestRate( double rate ) interestRate = rate ; package boy;public class ConstructionBank extends Bank double year ;public double computerInterest()super . year =( int ) year ;double r =year -( int ) year ; int day =( int )( r *1000);double yearInterest =super .computer

12、Interest(); / 【代码 1 】 /super 调用隐 藏的 computerInterest() 方法double dayInterest =day *0.0001* savedMoney ;interest =yearInterest +dayInterest ;System. out .printf( "%d元存在建设银行 %d年零d天的利息:f元 n" , savedMoney , super . year , day , interest );return interest ; package boy;public class BankOfDalian

13、extends Bank double year ;public double computerInterest() super . year =( int ) year ; double r =year -( int ) year ; int day =( int )( r *1000);double yearInterest =super .computerInterest(); / 【代码 2】 /super 调用隐 藏的 computerInterest() 方法double dayInterest =day *0.00012* savedMoney ;interest =yearIn

14、terest +dayInterest ;System. out .printf( "%d元存在大连银行 %d年零d天的利息:f元 n" , savedMoney , super . year , day , interest );return interest ;package boy;double interestRate=0.29;public class SaveMoney public static void main(String口args ) int amount =8000;ConstructionBank bank1 =new ConstructionBa

15、nk();bank1 . savedMoney =amount ;bank1 . year =8.236;bank1 .setInterestRate(0.035);double interest1 =bank1 .computerInterest(); BankOfDalian bank2 =new BankOfDalian();bank2 . savedMoney =amount ;bank2 . year =8.236;bank2 .setInterestRate(0.035);double interest2 =bank2 .computerInterest();System. out

16、 .printf( "两个银行利息相差 %f 元坨",interest2 - interest1 ); 8000元存在建设银行 8年零236天的利息:2428.800000 元8000元存在大连银行 8年零236天的利息:2466.560000 元两个银行利息相差 37.760000 元3)实验3面积之和Geometry.javapublic abstract class Geometry public abstract double getArea();package boy;public class TotalArea Geometry口 tuxing ;double

17、totalArea =0;public void setTuxing(Geometry口t )tuxing =t ;public double computerTatalArea()for (int i =0; i <tuxing . length ; i +) totalArea +=tuxing i .getArea();/【代码3】/用循环语句让tuxing的元素调用getArea 方法,并将返回的值累加到 totalAreareturn totalArea package boy;public class Rect extends Geometry double a, b;Rec

18、t( double a, double b) this . a=a; this . b=b;public double getArea() return a*b;/【代码1】/重写getArea() 方法package boy;public class Circle extends Geometry double r;Circle( double r) this . r=r ;public double getArea() return 3.14* r *r;/【代码2】/重写getArea() 方法 package boy;public class MainClass public stat

19、ic void main(String口 args ) Geometry口tuxing =new Geometry29; / 有 29 个 Geometry 对象for (int i =0; i <tuxing . length ; i +) /29 个 Geometry 对象分成两类if (i %2=0)tuxing i = new Rect(16+ i ,68); else if (i %2=1)tuxing i = new Circle(10+ i); TotalArea computer =new TotalArea();computer .setTuxing( tuxing )

20、;System. out .printf("各种图形的面积之和:n%f" , computer .computerTatalArea();各种图形的面积之和:58778.3600004)实验4 歌手大赛package boy;public interface ComputerAverage public double average( double x ); package boy;public class SongGame implements ComputerAveragepublicdouble average(double x )intcount =x. lengt

21、h ;double aver =0, temp =0;for ( int i =0; i <count ; i +)for ( int j =0; j <count ; j +)if (xj<xi)temp =x j ;x j = x i ;x i = temp ;for ( int i =0; i <count ; i +) aver =aver +x i ;if ( count >2)aver =aver /( count -2); else aver =0; return aver ;package boy;public class School imple

22、ments ComputerAveragepublic double average( double x ) / 【代码 1 】 / 重写 public doubleaverage(double x口)方法,返回数组 x口的元素的算术平方double sum=0;for (int i =0; i <x. length ; i +) sum+=x i ;return sum/x. length ; package boy;public class Estimator public static void main(String口 args ) double a=6.6,3.4,5.7,8.

23、9;double b=5.6,7.5,4.3,2.9;ComputerAverage computer ;computer =new SongGame();double result =computer .average( a); /【代码 2/computer调用 average(x口)方法,将数组a传递给参数xSystem. out .printf( "%n");System. out .printf("歌手最后得分:%5.3fn" , result );computer =new School();result =computer .average

24、( b); /【代码 3】/computer 调用 average(x口)方法,将数组b传递给参数xSystem. out .printf("学生平均体重:%-5.2f kg" , result ); 歌手最后得分:12.300 学生平均体重:5.07 kg5)实验5天气预报package boy;public interface WeatherState public void showState(); / 重写 public void showState() 方法 package boy;public class Weather WeatherState state ;

25、public void show() state .showState();public void setState(WeatherState s)state =s; package boy;public class CloudyLittleState implements WeatherStatepublic void showState()System. out .print( " 少云,有时晴。" ); package boy;public class HeavyRainState implements WeatherStatepublic void showStat

26、e() / 【代码2】 / 重写 public void showState()方法System. out .print( " 暴雨,有闪电。" ); package boy;public class LightRainState implements WeatherStatepublic void showState() / 【代码2】 / 重写 public void showState()方法System. out .print( " 小雨,转多云。" ); package boy;public interface WeatherState pub

27、lic void showState(); / 重写 public void showState() 方法 package boy;public class WeatherForecast public static void main(String args ) Weather weatherBeijing =new Weather();System. out .print("n 今天白天:" );weatherBeijing.setState(new CloudyDayState();weatherBeijing.show();System. out .print(&q

28、uot;n 今天夜间:" );weatherBeijing .setState(newLightRainState();weatherBeijing.show();System. out .print( "n 转:" );weatherBeijing .setState(newHeavyRainState();weatherBeijing.show();System. out .print("n 明天白天:" );weatherBeijing.setState(new LightRainState();weatherBeijing.show()

29、;System. out .print("n 明天夜间:" );weatherBeijing.setState(new CloudyLittleState();weatherBeijing.show();今天白天:少云,有时晴。今天夜间:小雨,转多云。转:暴雨,有闪电。明天白天:小雨,转多云。明天夜间:少云,有时晴。2、设计编写程序完成以下任务。1)根据要求修改实验2,参照建设银行再编写一个商业银行(广发行),让程序输出8000 元在广发行8 年零 212 天的利息。package boy; public class Bank int savedMoney ; int ye

30、ar ; double interest ; double interestRate =0.29; public double computerInterest() interest =year * interestRate * savedMoney ; return interest ; public void setInterestRate( double rate ) interestRate = rate ; package boy;public class ConstructionBank extends Bank double year ; public double comput

31、erInterest() super . year =( int ) year ; double r =year -( int ) year ; int day =( int )( r *1000);double yearInterest =super .computerInterest(); / 【代码 1 】 /super 调用隐 藏的 computerInterest() 方法double dayinterest =day *0.0001* savedMoney ;interest =yearInterest+dayInterest ;System. out .printf( "

32、;%d元存在建设银行 %d年零d天的利息:f元 n" , savedMoney , super . year , day , interest );return interest ; package boy;public class SaveMoney public static void main(String口args ) int amount =8000;ConstructionBank bankl =new ConstructionBank(); bankl . savedMoney =amount ;bankl . year =8.212;bankl .setInteres

33、tRate(0.035);double interestl =bank1 .computerInterest(); 加。0元存在建设银行&年零zii天的利息:240B.£000002)根据要求修改实验3,再增加一种几何图形(梯形),并让主类中的tuxing 的某些元素是梯形的上转型对象。package fourl;public abstract class Geometry public abstract double getArea();package fourl;public class TotalArea Geometry口tuxing ;double totalAre

34、a =0;public void setTuxing(Geometry口 t )tuxing =t ;public double computerTatalArea()for (int i =0; i <tuxing . length ; i +) totalArea +=tuxing i .getArea();/【代码3】/用循环语句让tuxing的元素调用getArea 方法,并将返回的值累加到 totalAreareturn totalArea ;package fourl;public class Trapezoid extends Geometrydouble x, y, z;

35、Trapezoid( double x, double y, double z)this . x=x;this . y=y;this . z=z;public double getArea()return z*( x+y)/2;package four1;public class MainClass public static void main(String口 args ) Trapezoid tuxing =new Trapezoid(4.6,4.6,7.9);/ 有 29 个 Geometry 对象double s =tuxing .getArea();System. out .prin

36、tf( "梯形的面积为:n%f" , s);两形的百积为:3)仿照实验5编写一个程序实现模拟水杯中的水在不同温度下可能出现的 状态。package four1;public class BoiledState implements WaterStatepublic void showState() System. out .println( "开水。"); package four1;public class IceState implements WaterStatepublic void showState()System. out .print(

37、"结冰。");package four1;public class LittleWarmState public void showState() System.out.println(implements WaterState"微凉。");package four1;public class WarmState implements WaterState public void showState() System.out.println( "温水。");/ 【代码 2】/ 重写 public void showState() 方法

38、package fourl;public class Water WaterState state ; public void show()state .showState();public void setState(WaterState s) state =s; package four1; public class WaterForecast public static void main(String口 args) Water waterState=new Water();System. out .print( waterState.setState( waterState.show(

39、);System. out .print( waterState.setState( waterState.show();"n"n温度在90-100时水杯水的状态:new BoiledState();温度在50-80 时水杯水的状态:new WarmState();");");System. out .print( waterState.setState( waterState.show(); System. out .print( waterState.setState( waterState.show();"n"n温度在30-50

40、时水杯水的状态:new LittleWarmState();温度在0度下时水杯水的状态: new IceState();");");package fourl;public interface WaterState public void showState();实验结果<tern'iinatea> waterrorecasi pava /温度在9。1 口口时水杯中水的状态开水n温度在50-90时水杯中水的状态 温水。温度在30-50时水杯中水的状态:微源*温度在。-30时水杯中水的状志二给冰。4)编写一个接口并创建两个实现该接口的类 A、Bo A B类

41、实现了接口的f 方法,A类的f方法内容为计算1! +3! +5!+9!并返回结果,B类的f方 法内容为计算2! +4! +6! +10!也返回结果;再编一个执行类,执行类运 行时要求通过接口回调方式用同一个对象实例分别调用A类的f方法和B类的f方法。package four1;public class A implements object public int f( int a, int b) int sum=0,temp=1;for (int i=a;i<=b;i=i+2) for (int j=1;j<=i;j+) temp*=j; sum+=temp; temp=1;ret

42、urn sum;package fourl;public class B implements object public int f( int a, int b) int sum=0,temp=1;for (int i=a;i<=b;i=i+2) for (int j=1;j<=i;j+) temp*=j; sum+=temp; temp=1; return sum;package four1;public interface object int f( int a, int b);package four1;public class Test public static voi

43、d main(String口 args) A a= new A();B b= new B();int sum1=a.f(1, 9);+sum1);"+sum2);int sum2=b.f(2, 10);System. out .println("1 ! +3! +5 ! +9 !的结果为:System. out .println("2 ! +4! +6 ! +10!的结果为:实验结果R Javadoc Declaration QConsole x Debug<terminated> Test (1) Java Application CPragranr

44、 Qose avajdk -12.0.2bin111 +3! +5! +9l 的造果为:3690472! +4! +6!的结果为:3669B665)(1)定义一个汽车类Vehicle ,要求如下:(知识点:类的继承 方法的覆盖)(a)属性包括:汽车品牌brand (String类型)、颜色color (String类型) 和速度speed (double类型)。(b)至少提供一个有参的构造方法(要求品牌和颜色可以初始化为任意值, 但速度的初始值必须为0)。(c)为属性提供访问器方法。注意:汽车品牌一旦初始化之后不能修改。(d)定义一个一般方法run(),用打印语句描述汽车奔跑的功能。定义测试类

45、VehicleTest ,在其main方法中创建一个品牌为“ benz”、颜 色为“black”的汽车。(2)定义一个Vehicle类的子类轿车类Car,要求如下:(a)轿车有自己的属性载人数loader (int类型)。(b)提供该类初始化属性的构造方法。(c)重新定义run(),用打印语句描述轿车奔跑的功能。(d)定义测试类Test,在其main方法中创建一个品牌为“ Hondd'、颜色 为“red”,载人数为2人的轿车。面向对象基础出过类似的,这个把继承引入了package four1;public class Car extends Vehicle int loader ;pu

46、blic Car(String brand, String color,double speed, int l) super (brand, color, speed);this . loader =l;public void run()System. out .println( "颜色为"+super .getColor()+ "的"+super .getBrand()+ 汽车的时速为:"+super .getSpeed(); package four1;public class Test public static void main(St

47、ring口 args) Car c= new Car( "Honda" , "red" ,300.0,20); c.run();package four1;public class Vehicle privateStringbrand ="BMW" / 汽车品牌privateStringcolor ="red" ; / 汽车颜色privatedoublespeed =0; /汽车时速publicString getColor() return colorpublic void setColor(String col

48、or) this . color = color;public double getSpeed() return speed ;public void setSpeed( double speed) this . speed = speed;public String getBrand() return brand ;public Vehicle(String brand, String color,double speed) this . brand =brand;this . color =color;this . speed =speed;public void run()System.

49、 out .println( brand +"汽车的时速为:"+speed );package four1;public class VehicleTest public static void main(String口 args) Vehicle v= | new Vehicle( "benz" , "black" ,200.0); v.run();实验结果<ieroiiiidieo> verncieieE>i JdVd /ppntdLiucij c:rnjyidi b电nz汽车的时速为:200.06) Cola公

50、司的雇员分为以下若干类:(知识点:多态)(1) ColaEmployee :这是所有员工总的父类,属性:员工的姓名,员工的生 日月份。方法:getSalary(int month)根据参数月份来确定工资,如果该月员工过生日,则公司会额外奖励100(2) SalariedEmployee : ColaEmployee 的子类,拿固定工资的员工。属性:月薪(3) HourlyEmployee : ColaEmployee的子类,按小时拿工资的员工,每月 工作超出160小时的部分按照1.5倍工资发放。属性:每小时的工资、每月工作的小时数(4) SalesEmployee : ColaEmployee

51、的子类,销售人员,工资由月销售额 和提成率决定。属性:月销售额、提成率(5)定义一个类Company在该类中写一个方法,调用该方法可以打印出某 月某个员工的工资数额,写一个测试类 TestCompany,在main方法,把若干各种 类型的员工放在一个 ColaEmployee数组里,并单元出数组中每个员工当月的工知识点:继承与多态package four1;public class ColaEmployee String name; / 员工姓名int month; /员工生日月份public String getName() return name;public void setName(S

52、tring name) this .name = name;public int getMonth() return month;public void setMonth( int month) this .month = month;int getSalary( int month) if (month = this .month)return 100;else return 0;package four1;public class Company extends ColaEmployeevoid print(String name,double salary, int month)Stri

53、ng Name=name;double Salary=salary;+Salary);int Month=month;System. out .println( "员工"+Name+"在"+Month+ "月"+"的薪资为:package four1;public class HourlyEmployee extends ColaEmployee double hours; /每月工作的时间double hsalary; /每小时的工资name, int month, double hours, double hsalary

54、)Company c= new Company。;public HourlyEmployee(String this .hours=hours;this .hsalary=hsalary;this .month=month; this .name=name;public double getHours() return hours;public void setHours( double hours) this .hours = hours;public double getHsalary() return hsalary;public void setHsalary( double hsal

55、ary) this .hsalary = hsalary;public int getSalary(int month)if (this .hours<=160)this .hsalary=this .hsalary*this .hours+ super .getSalary(month);c.print(name,hsalary,month);return 0; else this .hsalary=( this .hours-160)* this .hsalary*1.5+160* this .hsalary+ super .g etSalary(month);c.print(name,hsalary,month); return 0;package four1;public class SalariedEmployee extends ColaEmployee double salary; /员工固定薪资(按月)int month, double salary) Company c= new Company。;public SalariedEmployee(String name,this .name=name;t

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论