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();
}
虽然你这么实现可以,但是实际并没有用到多态
不用这么麻烦直接创建一个父类然后写一个方法再创建几个子类然后分别重写几个方法最后创建一个测试类用父类来引用子类的方法就可以了
Vehicle vehicle = new Bus();
vehicle.tranSport();
vehicle = new Steamship();
vehicle .tranSport();
vehicle = new Plane();
vehicle .tranSport();
Vehicle vehicle = new Bus();
vehicle.tranSport();
vehicle = new Steamship();
steamship.tranSport();
vehicle = new Plane();
plane.tranSport();
用一个父类的引用就可以了,没必要用三个
Java入门第二季 升级版
530652 学习 · 6091 问题
相似问题