Java类继承以及接口实现实例

Java类继承以及接口实现实例:这个实例非常容易理解,香港虚拟主机,网站空间,香港虚拟主机,贴在这里与大家共享。

Vehicle{ 3 private String name; cost; Vehicle(){ 8 }Vehicle(String name, double cost){ 12this.name = name; 13this.cost = cost; 14 } run(); stop(); String getName(){.name; 23 } getCost(){.cost; 27 } setName(String name){ 31this.name = name; 32 }setCost (double cost){ 35this.cost = cost; 36 } 37 } interRoadTax{ tax(); 44 }Bike extends Vehicle{ bikeType; Bike(){}Bike(String name, double cost, int type){.bikeType = type; 59 }setBikeType(int type){ 63this.bikeType = type; 64 } getBikeType(){.bikeType; 69 } run(){ 73System.out.println(“i am bike and running…..”); 74 } stop(){ 78System.out.println(“i am bike and stopping…..”); 79 } 80 }Car extends Vehicle implements interRoadTax{ numberOfPeople; Car(){}Car(String name, double cost, int numberOfPeople){.numberOfPeople = numberOfPeople; 95 } getNumberOfPeople(){.numberOfPeople;100 }setNumberOfPeople(int numberOfPeople){103this.numberOfPeople = numberOfPeople;104 } run(){108System.out.println(“i am car and running…..”);109 } stop(){113System.out.println(“i am car and stopping…..”);114 } tax(){118System.out.println(“the car tax is ” + getCost() * 0.1);119 }120 }Motor extends Vehicle implements interRoadTax{126 public Motor(){}127 public Motor(String name,double cost){128super(name,cost);129 } run(){132System.out.println(“i am Motor and running…..”);133 } stop(){136System.out.println(“i am Motor and stopping…..”);137 } tax(){140System.out.println(“the motor tax is ” + getCost() * 0.05);141 }142 } User{ id;149 private String name; Vehicle v; User(){}User(int _id,String _name){156id = _id;157name = _name;158 } print(){161System.out.println(“the user is “+ id +” – “+ name);162 } setV(Vehicle v){165this.v = v;166 } Vehicle getV(){.v;170 }171 } UserTest{ main(String[] args){177178User[] users = new User[3];179 180Vehicle v1 = new Bike(“fenghuang”, 500.00, 1);181Vehicle v2 = new Motor(“honda”, 10000.00);182Vehicle v3 = new Car(“polo”, 145678.00, 5);183184users[0] = new User(1,”yanming”);185users[0].setV(v1);186users[1] = new User(2,”laoxia”);187users[1].setV(v2);188users[2] = new User(3,”zhaomengran”);189users[2].setV(v3);System.out.println(“=====to begin test class=====”);193users[0].print();194users[0].getV().run();195users[1].print();196users[1].getV().run();197users[2].print();198users[2].getV().run();System.out.println(“=====to hand up Road Tax=====”);202for(User u : users){203Vehicle v = u.getV();204if(v instanceof Car){205Car c = (Car)v;206 c.tax();207 }(v instanceof Motor){210Motor m = (Motor)v;211 m.tax();212 }(v instanceof Bike){215System.out.println(” hah ,no tax”);216 }217 }218 }219 }我知道我不是一个很好的记录者,但我比任何人都喜欢回首自己来时的路,

Java类继承以及接口实现实例

相关文章:

你感兴趣的文章:

标签云: