实验4

《Java程序设计》实验4
本次实验考查知识点:
(1)Java语言中的类继承(extends)
(2)Java语言中的类封装(private)
(3)Java语言中的构造方法重写(override)
实验题目:
(1)定义一个名为Student的类,它继承Person类(Person类中包含String类型的name和int类型的age),其中定义sno(表示学号)和major(表示专业)两个成员变量和封装这两个变量的方法。编写主程序,检查新建类中的所有变量和方法。

(2)设计一个汽车类Auto,其中包含一个表示速度的double型的成员变量speed和表示启动的start()方法、表示加速的speedUp()方法以及表示停止的stop()方法。再设计一个Auto类的子类Bus表示公共汽车,在Bus类中定义一个int型的、表示乘客数量的成员变量passenger,另外定义两个方法gotOn()和gotOff()表示乘客上车和下车。编写一个应用程序,测试Bus类的使用。
Main.java

public class Main {
    public static void main(String[] args) {
        Bus bus = new Bus();
        bus.start();
        bus.speedUp(90);
        bus.stop();
        bus.gotOn(18);
        bus.gotOff(9);
    }
}

Auto.java

public class Auto {
    double speed;
    public void start() {
        System.out.println("启动");
    }
    public void speedUp(double speed) {
        this.speed=speed;
        System.out.println("加速"+speed+"km/h");
    }
    public void stop(){
        this.speed=0;
        System.out.println("停⽌"); }
}

Bus

class Bus extends Auto {
    int passenger; public void gotOn(int n) {
        passenger+=n;
        System.out.println("乘客上⻋"+passenger);
    }
    public void gotOff(int n) {
        passenger-=n;
        System.out.println("乘客下⻋"+passenger);
    }
}

image

(3)定义一个名为Cuboid的长方体类,使其继承Rectangle类(Rectangle类中包含double类型的length和width),其中包含一个表示高度的double型成员变量height,定义一个构造方法Cuboid(double length,double width,double height)和一个求长方体体积的volume()方法。编写一个应用程序,在其中求一个长、宽、高分别为10、5、2的长方体的体积。
Main.java

public class Main {
    public static void main(String[] args) {
        Cuboid cuboid=new Cuboid(12,6,3);
        System.out.println("volume=" +cuboid.volume());
    }
}

Rectangle.java

public class Rectangle {
    double length;
    double width;
    public Rectangle(double length,double width){
        this.length=length;
        this.width=width;
    }
    public double area(){
        return length*width;
    }
}

Cuboid.java

class Cuboid extends Rectangle{
    double height; public Cuboid(double length,double width,double height){
        super(length,width);
        this.height=height;
    }
    public double volume(){
        return area()*height;
    }
}

image

posted on 2023-08-22 15:10  逆袭怪  阅读(27)  评论(0编辑  收藏  举报