第四周作业:上机练习2类与对象
程序员文章站
2022-04-05 17:11:39
...
Part 1 类的定义
课堂练习1:
请定义一个交通工具(Vehicle)的类,其中有:
Ø 属性:速度(speed),体积(size)等
Ø 方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等
在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。
代码如下:
public class Vehicle {
int speed;
int size;
//time为行驶时间,length记录行驶路程
int time;
int length;
//设置行驶时间
void setTime(int t){
this.time = t;
System.out.println("行驶时间为"+this.time+"s");
}
void move(){
this.length = this.speed * this.time;
System.out.println(this.time+"s行驶路程为"+this.length);
}
void setSpeed(int speed){
this.speed = speed;
System.out.println("初始速度为"+this.speed);
}
void setSize(int size){
this.size = size;
System.out.println("该车辆可容纳"+this.size+"人");
}
void speedUp(){
System.out.println("加速5m/s");
this.speed +=5;
System.out.println("加速后速度为"+this.speed);
}
void speedDown(){
System.out.println("减速5m/s");
this.speed -=5;
System.out.println("减速后速度为"+this.speed);
}
}
public class testVehicle {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("++++++++++++++++++++++++");
System.out.println("小型车行驶概况:");
Vehicle smallCar = new Vehicle();
smallCar.setSize(5);
smallCar.setSpeed(60);
smallCar.setTime(100);
smallCar.move();
smallCar.speedUp();
smallCar.speedUp();
smallCar.speedDown();
System.out.println("++++++++++++++++++++++++");
System.out.println("大型车行驶概况:");
Vehicle bigCar = new Vehicle();
bigCar.setSize(32);
bigCar.setSpeed(120);
bigCar.setTime(10);
bigCar.move();
bigCar.speedUp();
bigCar.speedUp();
bigCar.speedDown();
}
}
Part 2 构造函数
课堂练习3:
以Point类为基础,定义一个平面中的Circle类:
1、 编写一个无参的构造函数;
2、 编写一个有参的构造函数;
在主函数中调用无参的构造函数生成圆的实例c1,调用有参的构造函数生成圆的实例c2,调用实例方法判断c1和c2是否相重叠。
代码如下:
//定义point类,记录点位置,计算两点距离
class Point {
double x,y;
Point(double x1,double y1){
this.x = x1;
this.y = y1;
}
double x_y_distance(Point P1){
double dist;
dist = Math.sqrt((x-P1.x)*(x-P1.x)-(y-P1.y)*(y-P1.y));
return dist;
}
}
//定义circle类,默认构造函数会生成一个x=3/y=4/r=5的圆
class Circle {
double x,y,r;
Circle(){
this.x = 3;
this.y = 4;
this.r = 5;
}
Circle(double x1,double y1,double r1){
this.x = x1;
this.y = y1;
this.r = r1;
}
}
//定义测试类,判断两个圆是否重叠
public class testCircle {
public static void main(String[] args) {
// TODO Auto-generated method stub
//圆c2,用户自定义圆心位置,及半径长度
Circle c1 = new Circle();
Circle c2 = new Circle(3,4,8);
Point p1 = new Point(c1.x,c1.y);
Point p2 = new Point(c2.x,c2.y);
//若两点之间距离小于半径之和,则两圆重叠
if(p2.x_y_distance(p1) < c1.r+c2.r){
System.out.println("两个圆重叠");
}else{
System.out.println("两个圆不重叠");
}
}
}
上一篇: SQL Server——自动化功能
下一篇: 原道M9i双系统平板怎么快速提速?
推荐阅读