变量被隐藏,方法被覆盖。将使用哪个变量取决于声明该变量的类。使用哪种方法取决于变量引用的对象的实际类。
class Car { public int gearRatio = 8; public String accelerate() { return "Accelerate : Car"; } } class SportsCar extends Car { public int gearRatio = 9; public String accelerate() { return "Accelerate : SportsCar"; } public void test() { } public static void main(String[] args) { Car car = new SportsCar(); System.out.println(car.gearRatio + " " + car.accelerate()); // 将打印出 8 Accelerate : SportsCar } }