题目:
【问题描述】
(1)定义一个车辆类Vehicle, 它有两个数据成员Name和 Price,代表车辆的名字、价格, 定义一个构造方法Vehicle(String n, int p), 定义一个显示车辆信息的方法show()。
(2)从Vehicle派生一个轿车类Car,定义一个表示品牌的数据成员type,定义一个有三个参数的构造方法Car(String n, int p, int t), 改写showme()方法以便显示轿车的信息。
(3)从Vehicle派生一个客车类Bus,定义一个表示座位数的数据成员seat,定义一个有三个参数的构造方法Bus(String n, int p, int s), 改写showme()方法以便显示客车的信息。
(4)在main方法中定义一个Vehicle引用,并分别用Car和Bus构造方法来初始化v,分别用v调用showme()方法以实现多态性。
【输入形式】name price type (回车) name price seat (回车) 数据之间空格隔开
【输出形式】Car's name=?,Price=?,type=? (回车) Bus's name=?,Price=?,seat=? (回车)
代码:新手第一次写,有什么不好的多多指教哈!
import java.util.Scanner; class Vehicle { String name;//两个成员变量 int price; public Vehicle(String name,int price) {//又一次方法重写哦 this.name=name; this.price=price; } public void show() { System.out.println(name); System.out.println(price); } } class Car extends Vehicle{ String type; public Car(String name,int price,String type) { super(name, price);//super表示想引用被隐藏了的方法 this.type=type; } public void show() {//方法重写 System.out.print("Car's name="+name); System.out.print(",Price="+price); System.out.println(",type="+type); } } class Bus extends Vehicle{ int seat; public Bus(String name,int price,int seat) { super(name, price);//同上哦 this.seat=seat; } public void show() {//方法重写 System.out.print("Bus's name="+name); System.out.print(",Price="+price); System.out.println(",seat="+seat); } } public class Test { public static void main(String[] args) { Scanner sc=new Scanner(System.in);//输入数据,注意输入的数据要与对应变量的类型一致,否则会报错哦 String CarName=sc.next(); int CarPrice=sc.nextInt(); String Type=sc.next(); String BusName=sc.next(); int BusPrice=sc.nextInt(); int Seat=sc.nextInt(); Car v1=new Car(CarName,CarPrice,Type); Bus v2=new Bus(BusName, BusPrice,Seat); v1.show(); v2.show(); } }