/*
汽车类
/
public abstract class MotoVehicle {
/
}
public MotoVehicle(String no,String brand,int perRend){
this.no=no;
this.brand=brand;
this.perRend=perRend;
}
}
/*
客车类
*/
public class Bus extends MotoVehicle{
private int seatCount;//座位数
public int getSeatCount() {
return seatCount;
}
public void setSeatCount(int seatCount) {
this.seatCount = seatCount;
}
public Bus(){
}
public Bus(String no,String brand,int perRent,int seatCount){
super(no,brand,perRent);//调用父类的构造函数
this.seatCount=seatCount;
}
/*
桥车类
*/
public class Car extends MotoVehicle{
private String type;//型号
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Car(){
}
public Car(String no,String brand,int perRent,String type){
super(no,brand,perRent);//调用父类的构造函数
this.type=type;
}
/*
/*
汽车业务类
/
public class Motooperation {
public MotoVehicle MotoleaseOut(String MotoType){
MotoVehicle moto=null;;
if(MotoType.equals("桥车")){
moto=new Car();//多态转型 类型提升 向上转型 把子类提升为父类
moto.leaseoutFlow();
}else if(MotoType.equals("客车")){
moto=new Bus();//多态转型 类型提升 向上转型 把子类提升为父类
moto.leaseoutFlow();
}
return moto;
}
}
/
汽车租赁管理类
*/
import java.util.Scanner;
public class RentMgrSys {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
Motooperation motoMrs=new Motooperation();
MotoVehicle moto=null;
System.out.println("欢迎来到汽车租赁公司!");
System.out.print("请输入要租赁的汽车类型: ");
System.out.print("1.桥车 2.客车");
int choose=input.nextInt();//汽车类型
String MotoType=null;
if(choose==1){
MotoType="桥车";
}else if(choose==2){
MotoType="客车";
}
moto=motoMrs.MotoleaseOut(MotoType);//获取租赁的汽车类型
System.out.print("请输入要租赁的天数");
int days=input.nextInt();
float money=moto.calRent(days);//租赁费用
System.out.println("分配给你的汽车牌号是:"+moto.getNo());
System.out.println("你需要支付的费用:"+money+"元");
input.close();
}
}
这句看不懂 float money=moto.calRent(days); moto是父类Motooperation的对象为什么调用的是子类的calRent()方法
moto是MotoVehicle类型的变量啊,motoMrs.MotoleaseOut(MotoType)得到的是MotoVehicle类的子类的对象。变量是在栈内存中的,对象是在堆内存中的。
moto变量能调用的方法由MotoVehicle类型决定,而具体怎么调用还要看子类对象,如果重写了calRent()方法就用子类的,没有就去找父类。
这是方法的重载解析。
父类变量引用子类对象,调用其方法时最后是子类的方法,这就是OO在Java中的体现。
基类是用来定义公共参数和公共方法的。子类是具体的实现。在具体算费的时候,这里就需要调用子类的函数了。
子类是具体实现的类,结算费用是,肯定会找子类对应的方法,这是多态啊
就是方法重写,参考 http://gengu.iteye.com/blog/1114422
注意,和方法重载不是一回事。也不要说成“多态”,这些都是不正确,不规范的说法。
建议你了解一下 moto是MotoVehicle类型的变量啊,motoMrs.MotoleaseOut(MotoType)得到的是MotoVehicle类的子类的对象。变量是在栈内存中的,对象是在堆内存中的。
moto变量能调用的方法由MotoVehicle类型决定,而具体怎么调用还要看子类对象,如果重写了calRent()方法就用子类的,没有就去找父类。
这是方法的重载解析。
多态,子类重写父类方法,动态加载时会调用子类的。
这是java中的多态,你看一下多态就行了