实验三中1~2

实验三  Java面向对象编程练习
1、 设计类来描述真实客观世界中的事物,使用类的成员变量来表示事物的属性和状态,使用类的成员方法来提供对成员变量的访问或修改
(1) 程序功能:设计一个用来描述汽车的类,使用类的非静态成员变量来表示汽车的车主姓名、当前的速率和当前方向盘的转向角度,使用类的非静态成员方法来表示改变汽车的速率和停车两个操作。
主方法与其他方法在同一类中(自己编写):
public class EXP3_1 {
  private String ownerName; //车主姓名
  private float curSpeed; //当前车速
  private float curDirInDegree; //当前方向盘转向角度
  public EXP3_1(String ownerName){
    this.ownerName=ownerName;
  }
  public EXP3_1(String ownerName, float speed, float dirInDegree){
   this(ownerName);//这句话是什么意思??????
   this.curSpeed=speed;
   this.curDirInDegree=dirInDegree;
}
  public String getOwnerName() { //提供对车主姓名的访问
    return ownerName;
  }
  public float getCurDirInDegree() { //提供对当前方向盘转向角度的访问
    return curDirInDegree;
  }
  public float getCurSpeed() { //提供对当前车速的访问
    return curSpeed;
  }
  public float changeSpeed(float curSpeed1) { //提供改变当前的车速
    return curSpeed1;
  }
  public String  stop(String s){ //提供停车
    return s;
  }
  public static void main(String[] args){
  EXP3_1 sc=new EXP3_1("张三",98f,23f);
  System.out.println("车主姓名:"+sc.getOwnerName());
  System.out.println("当前方向盘转向角度:"+sc.getCurDirInDegree());
  System.out.println("当前车速:"+sc.getCurSpeed());
  System.out.println("改变后车速:"+sc.changeSpeed(45f));
  System.out.println("在"+sc.stop("2号停车位")+"停车");
  }
}
运行老师源代码并改进后代码:
class EXP3_1 {
  private String ownerName; //车主姓名
  private float curSpeed; //当前车速
  private float curDirInDegree; //当前方向盘转向角度
  public EXP3_1(String ownerName){
    this.ownerName=ownerName;
  }
  public EXP3_1(String ownerName, float speed, float dirInDegree){
   this(ownerName);
   this.curSpeed=speed;
   this.curDirInDegree=dirInDegree;
}
  public String getOwnerName() { //提供对车主姓名的访问
    return ownerName;
  }
  public float getCurDirInDegree() { //提供对当前方向盘转向角度的访问
    return curDirInDegree;
  }
  public float getCurSpeed() { //提供对当前车速的访问
    return curSpeed;
  }
  public void changeSpeed(float curSpeed) { //提供改变当前的车速
    this.curSpeed = curSpeed;
  }
  public void stop(){ //提供停车
    this.curSpeed=0;
  }
    public String  stop1(String s){ //提供停车
    return s;
  }
}
public class EXP3_2 {
  public static void main(String[] args){
    EXP3_1 car=new EXP3_1("成龙",200f,25f);
    System.out.println("车主姓名: "+car.getOwnerName());
    System.out.println("当前车速: "+car.getCurSpeed());
    System.out.println("当前转向角度: "+car.getCurDirInDegree());
    car.changeSpeed(80);
    System.out.println("车速改变后为: " + car.getCurSpeed());
    car.stop();
    System.out.println("在调用stop()后, 车速变为: "+car.getCurSpeed());
    System.out.println("在"+car.stop1("2号停车位")+"停车");
  }
}

猜你喜欢

转载自yuan5hou.iteye.com/blog/1508221