目录
一、实验目的
熟悉类的创建方法;
掌握对象的声明与创建;
能利用面向对象的思想解决一般问题;
二、实验内容
类的创建;
对象的声明与创建;
类及对象的使用;
程序流程控制的实现。
三、实验步骤
编写一个 Java 应用程序,该程序中有两个类: Vehicle(用于刻画机动车)和 User(主类)。
四、实验代码
Vehicle.java
package demo;
public class Vehicle{
double speed;
int power;
void speedUp(int s){
this.speed=s;
}
void speedDown(int d){
this.speed=speed-d;
}
void setPower(int p){
this.power=p;
}
int getPower(){
return power;
}
double getSpeed() {
return speed;
}
}
User.java
package demo;
public class User{
public static void main(String args[]){
Vehicle car1,car2;
car1=new Vehicle();
car2=new Vehicle();
car1.setPower(128);
car2.setPower(76);
System.out.println("car1 power is :"+car1.getPower());
System.out.println("car2 power is :"+car2.getPower());
car1.speedUp(80);
car2.speedUp(80);
System.out.println("car1 existing speed is :"+car1.getSpeed());
System.out.println("car2 existing speed is :"+car2.getSpeed());
car1.speedDown(10);
car2.speedDown(20);
System.out.println("car1 existing speed is :"+car1.getSpeed());
System.out.println("car2 existing speed is :"+car2.getSpeed());
}
}
五、运行结果
car1 power is :128
car2 power is :76
car1 existing speed is :80.0
car2 existing speed is :80.0
car1 existing speed is :70.0
car2 existing speed is :60.0