代码如下,我的问题是wheels是父类的私有成员,为何在子类的构造方法中还能初始化wheels,难道子类的具体对象也可以拥有该成员?class Vehicle{
private int wheels; //使用了private,为何在子类中还可以初始化wheels呢
private double weight;
Vehicle(int wheels,double weight){
this.wheels = wheels;
this.weight = weight;
}
public void show(){
System.out.println("车轮数为:"+wheels+" 车重为:"+weight);
}
}
class Truck extends Vehicle{
private double load;
Truck(int wheels,double weight,double load){
super(wheels,weight);
this.load = load;
}
public void show(){
super.show();
System.out.println("载重量为:"+load);
}
}public class Test2 {
public static void main(String[] args){
Vehicle v1 = new Vehicle(4,200);
v1.show();
Truck t1 = new Truck(8,1000,2000);
t1.show();
}
}
private int wheels; //使用了private,为何在子类中还可以初始化wheels呢
private double weight;
Vehicle(int wheels,double weight){
this.wheels = wheels;
this.weight = weight;
}
public void show(){
System.out.println("车轮数为:"+wheels+" 车重为:"+weight);
}
}
class Truck extends Vehicle{
private double load;
Truck(int wheels,double weight,double load){
super(wheels,weight);
this.load = load;
}
public void show(){
super.show();
System.out.println("载重量为:"+load);
}
}public class Test2 {
public static void main(String[] args){
Vehicle v1 = new Vehicle(4,200);
v1.show();
Truck t1 = new Truck(8,1000,2000);
t1.show();
}
}
MARK一下。
不仅Vehicle的子类,其他不相关类也可以调用Vehicle的public constructor啊
因为这是父类干的活,自然就把父类的wheels初始化了。wheels是私有类型字段的,Truck不能访问,或者说不能使用。但是不能访问不表示不存在,所以还是必须交给父类的构造函数初始化的。