类与对象练习一 :请定义一个交通工具(Vehicle)的类

课堂练习1

请定义一个交通工具(Vehicle)的类,其中有:

 1. 属性:速度(speed),体积(size)等

 2.方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等

在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。



1.代码

(1)主类 TestVehicle.java

import java.util.Scanner;

public class TestVehicle {

public static void main(String[]args) {

 Scanner sc=new Scanner(System.in);            //创建对象sc

 int sp=sc.nextInt(); //输入速度sp的值

 int si=sc.nextInt(); //输入体积si的值

 Vehicle car=new Vehicle(); //创建交通工具对象car

 car.setSpeed(sp); //调用setSpeed方法,给速度赋值

car.setSize(si); //调用setSize方法,给体积赋值

car.printvehicle(); //调用printvehicle方法,输出car的速度和体积

System.out.print("汽车的速度增加了:");

int up=sc.nextInt(); //输入速度增加的值

car.speedUp(car,up); //调用speedUp方法,输出速度增加后的值

System.out.print("汽车的速度减少了:");

int down=sc.nextInt(); //输入速度减少的值

        car.speedDown(car,down); //调用speedDown方法,输出速度减少之后的值

}

}

(2) Vehicle.java

 

public class Vehicle {

int speed;

int size;

int up;

int down;

void move() {//定义方法move

 

}

    void setSpeed(int sp ) {//定义方法setSpeed ,为speed赋值

  speed=sp;

}

void setSize(int si) {//定义方法setSize,为size赋值

size=si;

}

void printvehicle() {//定义方法printvehicle,输出汽车速度和体积

System.out.println("汽车的速度为"+speed+"千米/时");

System.out.println("汽车的体积为"+size+"立方米");

}

void speedUp(Vehiclecarr,int upp) {//定义方法speedUp,输出加速后的速度

up=carr.speed+upp;

System.out.println("汽车加速后的速度为:"+up+"千米/时");

}

void speedDown(Vehiclecarr,int downn) {//定义方法speedDown,输出减速后的速度

down=carr.speed-downn;

System.out.println("汽车减速后的速度为:"+down+"千米/时");

}

}

2.运行截图

  • 4
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值