好喜欢taeyeon啊_
2015-01-16 15:51
package com.yyh.nuaa; public class Car { //描述车辆的属性 protected static String name; protected static int cost; protected static int passenger; protected static int cargo; //构造方法 public Car(String name,int cost,int passenger,int cargo){ this.name = name; this.cost = cost; this.passenger = passenger; this.cargo = cargo; //System.out.println("车辆编号" + "\t" + "车辆名称" + "\t" + "租金" + "\t" + "载客,货量"); } public static String getName() { return name; } public static int getCost() { return cost; } public static int getPassenger() { return passenger; } public static int getCargo() { return cargo; } }
package com.yyh.nuaa; public class Car_multi extends Car { public Car_multi(String name,int cost,int passenger,int cargo){ super(name,cost,passenger,cargo); //System.out.println(Car_multi.this.getName() + "\t\t" + Car_multi.this.getCost() + "\t\t" + Car_multi.this.getCargo() + "吨," + Car_multi.this.getPassenger() + "人"); } }
package com.yyh.nuaa; public class Car_passenger extends Car { public Car_passenger(String name,int cost,int passenger,int cargo){ super(name,cost,passenger,cargo); //System.out.println(Car_passenger.this.getName() + "\t\t" + Car_passenger.this.getCost() + "\t\t" + Car_passenger.this.getPassenger() + "人"); } } package com.yyh.nuaa; public class Car_truck extends Car { public Car_truck(String name,int cost,int passenger,int cargo){ super(name,cost,passenger,cargo); //System.out.println(Car_truck.this.getName() +"\t\t" + Car_truck.this.getCost() + "\t\t" + Car_truck.this.getCargo() + "吨"); } } package com.yyh.nuaa; public class Main_car { public static void main(String[] args) { Car[] CarsRented = {new Car_passenger("奥迪A4",500,4,0), new Car_passenger("马自达6",400,4,0), new Car_multi("皮卡雪6",450,4,2), new Car_passenger("金龙",800,20,0), new Car_truck("松花江",400,0,5), new Car_truck("依维柯",900,0,20)}; for (int i = 0; i < CarsRented.length; i++) { System.out.println(CarsRented[i].getName()); } } } 为什么输出是这样啊? 0依维柯 1依维柯 2依维柯 3依维柯 4依维柯 5依维柯
为什么把Car类里的属性都定义成static,static表示共享的数据,虽然生成对象了,但其实每个对象的name值和其他值都是共享的,每生成一个对象就修改一次值,所以最好name等变量存放的就是最后一个对象的数据。把static都去掉试试。
Java入门第二季 升级版
530562 学习 · 6091 问题
相似问题