(OJ)Java面向对象-编写汽车类

编写汽车类

Problem Description

1.实验目的
    (1) 熟悉类的创建方法
    (2) 掌握对象的声明与创建
    (3) 能利用面向对象的思想解决一般问题
 
2.实验内容 
   编写一个java程序,设计一个汽车类Vehicle,包含的属性有车轮的个数wheels和车重weight。小汽车类Car是Vehicle的子类,包含的属性有载人数loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有构造方法和输出相关数据的方法。

3.实验要求
   补充完整下面的代码

  public class Main{
    public static void main(String[] args){
        Vehicle v=new Vehicle(8,10.00);
        smallCar c=new smallCar(6);
        Truck t=new Truck(10);
        v.disMessage();
        c.disM();
        t.disM2();
        t.disM3();
   }
}
    // 你的代码

Output Description

The number of wheels in this car is 8, weight is 10.0
This car can carry 6 persons
The load of this truck is 10
The number of wheels in this truck is 8, weight is 10.0, can carry 6 persons, load of this truck is 10

解题代码

// Vehicle 类
class Vehicle{
    
    
    // wheels 车轮个数
    public int wheels;
	// 重量
    public double weight;

    // 带参构造方法
    public Vehicle(int wheels, double weight) {
    
    
        this.wheels = wheels;
        this.weight = weight;
    }
	
    // 无参构造方法
    public Vehicle() {
    
    
    }
	
    // 打印信息
    public void disMessage(){
    
    
        System.out.println("The number of wheels in this car is " + wheels + ", weight is " + weight);
    }
}

// smallCar类继承Vehicle类
class smallCar extends Vehicle{
    
    
    // loader 载人数
    public int loader;
	// 带参构造 三个参数
    public smallCar(int wheels, double weight, int loader) {
    
    
        // 调用父类构造器
        super(wheels, weight);
        this.loader = loader;
    }

    // 带参构造 一个参数
    public smallCar(int loader) {
    
    
        // 调用父类构造 根据题目输出 wheels = 8 weight10.00
        super(8, 10.00);
        this.loader = loader;
    }
	
    // 无参构造
    public smallCar() {
    
    
    }
	// 打印信息
    public void disM(){
    
    
        System.out.println("This car can carry " + loader + " persons");
    }
}
// Truck类继承smallCar类
class Truck extends smallCar{
    
    
    // payload 载重量
    private int payload;
	
    // 带参构造 一个参数
    public Truck(int payload) {
    
    
        // 调用父类构造 根据题目输出 loader = 6
        super(6);
        this.payload = payload;
    }
	
    // 带参构造 四个参数
    public Truck(int wheels, double weight, int loader, int payload) {
    
    
        // 调用父类构造
        super(wheels, weight, loader);
        this.payload = payload;
    }
	// 无参构造
    public Truck() {
    
    
    }
	
    // 打印信息
    public void disM2(){
    
    
        System.out.println("The load of this truck is " + payload);
    }

    // 打印信息
    public void disM3(){
    
    
        System.out.println("The number of wheels in this truck is " + wheels + ", weight is " + weight + ", can carry " + loader + " persons, load of this truck is " + payload);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112524312
今日推荐