实验报告
实验课程: Java面向程序设计实验 实验内容: 类与对象
院 (系): 计算机学院 专 业: 计算机科学与技术(软件工程方向) 班 级: 学生姓名: 学 号:
指导教师:
2014年 3 月 26 日
一、实验目的:
1、掌握用类来封装对象的属性和行为的方法; 2、掌握对象的组合和参数传递;
3、掌握类变量与实例变量、类方法与实例方法的区别。
二、实验内容
(-)实验题目一:编写一个java应用程序,该程序中有两个类:Tank和Fight具体要求如下:
1、Tank类有一个double类型变量speed,用于刻画坦克的速度;一个int型变量bulletAmount,用于刻画坦克的炮弹数量。定义了speedUp()和speedDown()方法,体现坦克有加速、减速行为;定义了setBulletAmount(int p)方法,用于设置坦克炮弹的数量;定义了fire()方法,体现坦克有开炮行为。
1.程序源代码:
package p1;
public class Tank { }
double getSpeed(){ }
void fire(){ } }
package p1;
public class Fight {
public static void main(String args[]){
Tank tank1,tank2; tank1=new Tank(); if(bulletAmount>=1){
bulletAmount=bulletAmount-1;
System.out.println(\打出一发炮弹\); } else{
System.out.println(\没有炮弹了,无法开火\); }
return speed; double speed; int bulletAmount; void speedUp(int s){ speed=s+speed; }
void speedDown(int d){ }
void setBulletAmount(int m){ }
return bulletAmount;
bulletAmount=m; if(speed-d>=0)
speed=speed-d; speed=0; else
int getBulletAmount(){
}
tank2=new Tank();
tank1.setBulletAmount(10); tank2.setBulletAmount(10);
System.out.println(\的炮弹数量:\+tank1.getBulletAmount()); System.out.println(\的炮弹数量:\+tank2.getBulletAmount()); tank1.speedUp(80); tank2.speedUp(90);
System.out.println(\目前的速度:\+tank1.getSpeed()); System.out.println(\目前的速度:\+tank2.getSpeed()); tank1.speedDown(15); tank2.speedDown(30);
System.out.println(\目前的速度:\+tank1.getSpeed()); System.out.println(\目前的速度:\+tank2.getSpeed()); System.out.println(\开火:\); tank1.fire();
System.out.println(\开火:\); tank2.fire(); tank2.fire();
System.out.println(\的炮弹数量:\+tank1.getBulletAmount());
System.out.println(\的炮弹数量:\+tank2.getBulletAmount()); }
2.实验结果:
图1 3、实验课后练习:
(1)改进speedUp方法,使得Tank类的对象调用它能将Speed值超过220; 答:只需加入如下代码,其实验结果如图2:
void speedUp(int s){
if(s+speed<=200)//加入判断语句即可 speed=s+speed; }
图2:tank2加速200,超过220,所以tank2数值保持不变
(2)增加一个刹车方法:void brake(),Tank类的对象调用它将speed的值变为0.
答:只需增加如下代码:其结果如图3所示:
void brake(){
}
speed=0;
System.out.println(\加速200:\ tank2.speedUp(200);
System.out.println(\调用brake后:\ tank2.brake();