当前位置 : 主页 > 编程语言 > c++ >

17Java基础练习--面向对象

来源:互联网 收集:自由互联 发布时间:2021-07-03
(*)定义机动车类,具有属性:车牌号、车速和载重量,具有功能:加速、减速。一个构造方法没有形参,在方法中将车牌号设置为“辽A1234”,速度为100,载重量为50;另一个构造方
(*)定义机动车类,具有属性:车牌号、车速和载重量,具有功能:加速、减速。一个构造方法没有形参,在方法中将车牌号设置为“辽A1234”,速度为100,载重量为50;另一个构造方法用形参为对象的所有属性赋值。 在主类中创建两个机动车对象,创建第一个时调用无参数的构造方法,使其加速10。创建第二个时调用有参数的构造方法,使其车牌号为“辽B5678”,车速为80,载重量为20,并让其减速20。最后输出两辆车的所有信息
package gh;

public class vehicle {
String vehicl_Number;
int    vehicl_speed;
int    vehicl_loadVolume;

public vehicle() {
	super();
	vehicl_Number="辽A1234";
    vehicl_speed=100;
    vehicl_loadVolume=50;
}

public vehicle(String vehicl_Number, int vehicl_speed, int vehicl_loadVolume) {
	super();
	this.vehicl_Number = vehicl_Number;
	this.vehicl_speed = vehicl_speed;
	this.vehicl_loadVolume = vehicl_loadVolume;
}

int accelerate(int x){
	vehicl_speed+=x;
	return vehicl_speed;
	
}
int decelerate(int x){
	vehicl_speed-=x;
	return vehicl_speed;
}

}

package gh;

public class text8 {
public static void main(String[] args) {
	vehicle myVehicle1=new vehicle();
	vehicle myVehicle2=new vehicle("辽B5678",80,20);
	myVehicle2.decelerate(20);
	System.out.println(myVehicle1.vehicl_Number+" "+myVehicle1.vehicl_speed+" "+myVehicle1.vehicl_loadVolume);
	System.out.println(myVehicle2.vehicl_Number+" "+myVehicle2.vehicl_speed+" "+myVehicle2.vehicl_loadVolume);

}
}
网友评论