高山彝人
2016-01-09 19:21
public class Car{ private int carMoney; //汽车租金 private String carName; //汽车名字 private int carNumb; //汽车序列号 private int carryNum; //载货量 private int passengerNum;//载客人数 public Car(int carNumb,String carName,int carMoney,int passengerNum,int carryNum){ this.carMoney = carMoney; this.carName = carName; this.carNumb = carNumb; this.carryNum = carryNum; this.passengerNum = passengerNum; } public int getCarMoney() { return carMoney; } public void setCarMoney(int carMoney) { this.carMoney = carMoney; } public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } public int getCarNumb() { return carNumb; } public void setCarNumb(int carNumb) { this.carNumb = carNumb; } public int getCarryNum() { return carryNum; } public void setCarryNum(int carryNum) { this.carryNum = carryNum; } public int getPassengerNum() { return passengerNum; } public void setPassengerNum(int passengerNum) { this.passengerNum = passengerNum; } public void showInfo() { // TODO Auto-generated method stub } } class Sedan extends Car{ public Sedan(int carNumb,String carName,int carMoney,int passengerNum,int carryNum){ super(carNumb,carName,carMoney,passengerNum,carryNum); } } class Pickup extends Car{ public Pickup(int carNumb,String carName,int carMoney,int passengerNum,int carryNum){ super(carNumb,carName,carMoney,passengerNum,carryNum); } }
如上所示,不是说私有属性无法继承吗?那么用super调用构造函数时初始化的是什么?子类没有继承父类的属性啊。可是用以上代码却可以调用子类的构造方法初始化父类的属性。怎么回事?
super调用的这段代码:
public Car(int carNumb,String carName,int carMoney,int passengerNum,int carryNum){ this.carMoney = carMoney; this.carName = carName; this.carNumb = carNumb; this.carryNum = carryNum; this.passengerNum = passengerNum; }
这段代码中的this,如果你是创建Sedan,那么this就是Sedan,如果是Pickup,那么this 就是Pickup。
虽然父类的字段是private,但你提供了构造方法去访问。
同学,怎样在这里提问
恩,谢谢。这两天又学习了一下,弄清楚了,发现我其实搞复杂了,搞重复了。其实在子类当中声明有参构造器,直接在构造器当中用this调用set方法赋值就OK了。
Java入门第二季 升级版
530650 学习 · 6091 问题
相似问题
回答 1
回答 3
回答 2
回答 2
回答 1