课后练习题

来源:10-1 Java 中的多态

qq_斌_37

2019-01-23 00:29

//定义一个交通工具的父类Vehicle

public class Vehicle {

    private String tool;     //定义运输工具

    private String way;     //定义运输方式

    private int amount;     //定义运输人数

    public void tranSport(String tool,String way,int amount){

        this.tool = tool;

        this.way = way;

        this.amount = amount;

    }

    public void tranSport(){

        System.out.println(tool+"可以在"+way+"载客"+amount+"人");

    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------

//公共汽车子类

public class Bus extends Vehicle{

    public Bus(){

        super.tranSport("公共汽车","陆地",40);

    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------

//轮船子类

public class Steamship extends Vehicle{

    public Steamship(){

        super.tranSport("轮船","海上",200);

    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------

//飞机子类

public class Plane extends Vehicle{

    public Plane(){

        super.tranSport("飞机","天空",400);

    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------

//输出结果

    public static void main(String[] args){

       //利用对象的多态创建实例

        Vehicle bus = new Bus();

        bus.tranSport();

        Vehicle steamship = new Steamship();

        steamship.tranSport();

        Vehicle plane = new Plane();

        plane.tranSport();

    }


写回答 关注

4回答

  • 北顾岛城
    2019-02-12 21:08:06

    虽然你这么实现可以,但是实际并没有用到多态

  • 这鱼又溺水了
    2019-02-03 19:55:56

    不用这么麻烦直接创建一个父类然后写一个方法再创建几个子类然后分别重写几个方法最后创建一个测试类用父类来引用子类的方法就可以了

  • 滑稽ing
    2019-01-27 17:29:11

    Vehicle vehicle = new Bus();

    vehicle.tranSport();

    vehicle = new Steamship();

    vehicle .tranSport();

    vehicle = new Plane();

    vehicle .tranSport();


  • 滑稽ing
    2019-01-27 17:05:57

    Vehicle vehicle = new Bus();

    vehicle.tranSport();

    vehicle = new Steamship();

    steamship.tranSport();

    vehicle = new Plane();

    plane.tranSport();

    用一个父类的引用就可以了,没必要用三个


Java入门第二季 升级版

课程升级!以终为始告别枯燥,在开发和重构中体会Java面向对象编程的奥妙

530652 学习 · 6091 问题

查看课程

相似问题