//刻画机动车
public class Vehicle {
//声明double型变量speed,刻画速度
double speed;
//声明int型变量power刻画功率
int power;
void speedUp(int s)
{
//将参数s的值与成员变量speed的和赋值给成员变量speed
speed=s+speed;
}
void speedDoewn(int d)
{
//将成员变量speed与参数d的差赋值给成员变量speed
speed=speed+d;
}
void setPower(int p)
{
//将参数p的值赋值给成员变量power
power=p;
}
int getPower()
{
//返回成员变量power的值
return power;
}
double getSpeed()
{
return speed;
}
}
//主类
public class User {
public static void main(String args[])
{
Vehicle car1,car2;
//使用new运算符和默认值的构造方法创建对象car1
car1=new Vehicle();
car2=new Vehicle();
car1.setPower(128);
car2.setPower(76);
System.out.println("car1的功率是:"+car1.getPower());
System.out.println("car2的功率是:"+car2.getPower());
//car1调用speedUp()方法将自己的speed的值增加80
car1.speedUp(80);
//car2调用speedUp()方法将自己的speed的值增加80
car2.speedUp(80);
System.out.println("car1目前的速度是:"+car1.getSpeed());
System.out.println("car2目前的速度是:"+car2.getSpeed());
car1.speedDoewn(10);
car2.speedDoewn(20);
System.out.println("car1目前的速度是:"+car1.getSpeed());
System.out.println("car2目前的速度是:"+car2.getSpeed());
}
}
Chapter 4
最新推荐文章于 2022-10-12 00:03:34 发布