java中通过父类引用创建子类对象后,输出子类的属性值不是子类中所写的属性值,而是继承父类的,为什么
package com.hu; public class Vehicle { public int num; public String mode; public String type; public void ability(){ System.out.println("交通工具具有载人出行的能力"); System.out.println("num:"+num+"\nmode:"+mode+"\ntype:"+type); } } public class Car extends Vehicle { public int num=6; public String mode="陆行"; public String type="汽车"; public void ability(){ System.out.println("汽车具有载人陆行的能力"); System.out.println("num:"+num+"\nmode"+mode+"\ntype"+type); } @Override public String toString() { return "Car [num=" + num + ", mode=" + mode + ", type=" + type + "]"; } public class Initail { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); Vehicle car = new Car(); vehicle.ability(); System.out.println(); car.ability(); System.out.println(); System.out.println(car.num+"\n"+car.mode+"\n"+car.type);//就是这行 System.out.println(); System.out.println(car); } }
为什么
System.out.println(car.num+"\n"+car.mode+"\n"+car.type);
这句输出的是
0
null
null
而不是
6
陆行
汽车