一、 实验内容
- 模拟人开车的问题:请同学们各自讨论,独立完成。
- 模拟人开车:
- 根据模拟开车这问题,给出所需的类;
- 模拟中人如何作用于车对象?
- 模拟中车加速等细节代码,用类似打印“车加速中…”的简易代码。
- 实验目的
- 掌握类的声明;
- 掌握对象的创建;
- 掌握方法的定义和调用;
- 掌握构造方法执行机理和使用;
- 掌握private、public等修饰符;
- 掌握this的各种用法;
- 掌握重载的定义。
二、类图/类关系图
三、程序与测试
Car类
public class Car {
private int speed = 0;
private String Brand;
private int numOfCar = 0;
public int weel;
public void setWeel(){
weel = 4;
//System.out.println("汽车的车轮数:"+weel);
}
public Car(int speed, String brand) {
System.out.println("购入了一辆小车");
numOfCar++;
this.speed = speed;
Brand = brand;
}
public Car() {
System.out.println("购入了一辆小车");
numOfCar++;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public String getBrand() {
System.out.println("车的品牌是:"+Brand);
return Brand;
}
public void setBrand(String brand) {
Brand = brand;
}
public int getNumOfCar() {
System.out.println("小王新增了"+numOfCar+"辆车");
return numOfCar;
}
public void setNumOfCar(int numOfCar) {
this.numOfCar = numOfCar;
}
public void addSpeed(int s){
System.out.println("车正在加速");
speed += s;
System.out.println("车加速到"+speed+"m/s了");
if(speed>15) System.out.println("请注意限速");
}
public void slowDown(int s){
speed -=s;
if(speed>0)
System.out.println("车正在减速,车速为:"+speed+"m/s");
if(speed<0) System.out.println("正在倒车,请注意车后方来车,目前车速为"+speed+"m/s");
if(speed == 0) System.out.println("车已经停止行驶");
}
}
Moto类
package edu.moth10.CARS;
public class Moto extends Car{
private Moto(int weel){}//一个private类型的构造方法,可用来控制对象的创建
public Moto(){}
public void setweel(){
super.setWeel();
System.out.println("super.weel:"+super.weel);
weel = 2;
System.out.println("摩托车的车轮数:"+weel);
}
public void Moto() {
Moto moto = new Moto(0);
System.out.println("调用private类型的构造方法成功!!!");
}
}
people类
public class People {
private Car car = null;
private String name;
public People() {
}
public People(Car car,String name) {
this.car = car;
this.name = name;
System.out.print(name);
}
public Car getCar() {
return car;
}
public void setCar(Car car){
this.car= car;
}
}
Main类包含main函数
package edu.moth10.CARS;
import java.applet.AudioClip;
public class Main {
public static void main(String[] args) {
People one = new People(null,"老王");
Car car = new Car(0, "Audi");//Car创建第一次对象
Car car2 = new Car();//Car创建第二次对象
one.setCar(car);
one.getCar().getBrand();
one.getCar().getNumOfCar();
one.getCar().setWeel();
System.out.println("车主已上车");
one.getCar().addSpeed(5);
one.getCar().addSpeed(11);
one.getCar().slowDown(5);
one.getCar().slowDown(6);
one.getCar().slowDown(6);
one.getCar().slowDown(-1);
Moto moto = new Moto();
moto.Moto();
moto.setweel();
int num = moto.getNumOfCar();
System.out.println("共有Car:"+num);//通过Car的子类Moto又一次调用了Car里的getNumOfCar方法
//其中NumOfCar可以用来统计类创建对象的次数
}
}