编写一个继承自Vehicle的Bus类。Bus类的实例总是必须具有一位命名的驾驶员。在Bus
问题详情
编写一个继承自Vehicle的Bus类。Bus类的实例总是必须具有一位命名的驾驶员。在Bus的构造函数中,确保你的代码期望并存储驾驶员的名字。此外,Bus类还应该具有访问器方法和修改器方法,用于返回和更改驾驶员的名字。
请帮忙给出正确答案和分析,谢谢!
参考答案
正确答案:clas s Bus extends Vehicle{private String driver;public Bus(String driver)f//A"convenience constructorH that defaults all the//parameters except for driver name.The"this"//Says create a bus passing the 4 default parameter//values plus the driver name to the other{/constructor for the Bus class.this("GM""Metro"42"Siiver"driver);}public Bus(String mkString mdlint maxOccString clrString driver){//super says create a vehicle instance for this bus//super invokes the vehicle(superclass)constructorsuper(mkmdlmaxOccclr);//We also need to store the name of the bus driver.//this.driver refers to the private instance variable//that has the same name as the constructor parameter this.driver=driver;}publ ic String getDriver(){return driver;}public void setDriver(String driver){this.driver=driver;}publ ic static void main(String[]args){//A main method for testing use onlyBus firstBus=new Bus("Joe");Bus secondBus=new Bus("Mercedes""B302"60"Black" "Mary");System.out.println("First bus:"+firstBus.getMake()+"driven by"+firstBus.getDriver());System.out.println("Second bus:"+secondBus.getMake()+"driven by"+secondBus.getDriver());secondBus.setDriver("David");System.out.println("Second bus:"+secondBus.getMake()+"driven by"+secondBus.getDriver());}}
classBusextendsVehicle{privateStringdriver;publicBus(Stringdriver)f//A"convenienceconstructorHthatdefaultsallthe//parametersexceptfordrivername.The"this"//Sayscreateabuspassingthe4defaultparameter//values,plusthedrivername,totheother{/constructorfortheBusclass.this("GM","Metro",42,"Siiver",driver);}publicBus(Stringmk,Stringmdl,intmaxOcc,Stringclr,Stringdriver){//supersayscreateavehicleinstanceforthisbus//superinvokesthevehicle(superclass)constructorsuper(mk,mdl,maxOcc,clr);//Wealsoneedtostorethenameofthebusdriver.//this.driverreferstotheprivateinstancevariable//thathasthesamenameastheconstructorparameterthis.driver=driver;}publicStringgetDriver(){returndriver;}publicvoidsetDriver(Stringdriver){this.driver=driver;}publicstaticvoidmain(String[]args){//AmainmethodfortestinguseonlyBusfirstBus=newBus("Joe");BussecondBus=newBus("Mercedes","B302",60,"Black","Mary");System.out.println("Firstbus:"+firstBus.getMake()+"drivenby"+firstBus.getDriver());System.out.println("Secondbus:"+secondBus.getMake()+"drivenby"+secondBus.getDriver());secondBus.setDriver("David");System.out.println("Secondbus:"+secondBus.getMake()+"drivenby"+secondBus.getDriver());}}