Java实验第二次
public class MyProgram {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyProgram2 my = new MyProgram2(111, "222");
System.out.println(my.toString());
}
}
class MyProgram2 {
private int date;
private String str;
public MyProgram2() {
}
public MyProgram2(int date, String str) {
this.date = date;
this.str = str;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "MyProgram{" +
"date=" + date +
", str='" + str + '\'' +
'}';
}
}
public class Vehicle {
public float journey;
public int wheelNum;
public int loadNum;
public int driveSpeed;
public Vehicle(){
journey = 100.3f;
wheelNum = 4;
loadNum = 1;
}
public void driveAt(int speed){
if(speed >= 60){
System.out.println("你的速度行驶过快,重新以40速度行驶");
driveSpeed = 40;
}
if(speed <= 60){
driveSpeed = speed;
}
}
public void plough(){
System.out.println("journey:"+journey);
System.out.println("wheelNum:"+wheelNum);
System.out.println("loadNum:"+loadNum);
System.out.println("现在的driveSpeed:"+driveSpeed);
}
}
package text2.vehicle;
public class Vehicle_text extends Vehicle{
public static void main(String[] args) {
// TODO Auto-generated method stub
Vehicle v = new Vehicle();
v.driveAt(80);
v.plough();
System.out.println("==============");
Vehicle v2 = new Vehicle();
v.driveAt(30);
v.plough();
}
}
3 问题描述:一辆Car有(has)四个轮子(Wheels)和一个发动机(Engine)。现在要求用组合方法设计类Car、类Wheel和类Engine。
(1) 类Engine 有字符串属性type记录发动机的型号;
有构造方法,可设置发动机的型号;
有方法start()启动引擎(输出下面样例中包含发动机型号和“starts”的字符串)。
(2)类Wheel有字符串属性type记录轮胎的型号,有整数类型属性index记录当前轮胎编号(1:front-left,2:front-right,3:back-left,4:back-right);
有构造方法,可设置轮胎的型号和编号;
有方法roll()表示轮胎正在转动(输出下面样例中包含轮胎型号、轮胎位置和“rolling”的字符串)。
(3)类Car有字符串属性model记录轿车的型号,有属性wheels[]和engine,分别是Wheel类对象数组和Engine类对象;
有构造方法,参数是三个字符串,分别表示轿车的型号、轮胎型号和发动机的型号;
有方法changeWheel()可以改变指定轮胎的型号;
有方法start(),先输出下面样例中包含轿车型号和“firing”的字符串,然后调用engine的start(),再调用所有轮胎的roll(),最后显示轿车型号和“running”。
public class Car {
private String model; //model记录轿车的型号
private String wheel; //轮子
private String engine; //发动机
private String []wheels=new String[5]; //Wheel类对象数组
public Car(String model, String wheel, String engine) {
//构造方法
super();
this.model = model;
this.wheel = wheel;
this.engine = engine;
for(int i=0;i<wheels.length;i++){
//把wheel的数据循环传入wheel对象数组中
wheels[i]=wheel;
}
}
public void changeWheel(int index,String type){
//整数类型属性index记录当前轮胎编号
wheels[index]=type; //通过index编号,修改轮胎类型
}
public void start(){
System.out.println("Car"+model+"firing!");
Engine e=new Engine(this.engine);
e.start();
for(int i=0;i<wheels.length;i++){
Wheel w=new