Consider the following base/derived classes:
public class Car {
private int cylinders;
public Car(int cyl) {
cylinders = cyl;
}
public int getCylinders() {
return cylinders;
}
}
public class SportsCar extends Car {
private int topSpeed;
public SportsCar(int cyl, int top) {
super(cyl);
topSpeed = top;
}
public int getTopSpeed() {
return topSpeed;
}
}
Now, consider the following two objects:
SportsCar lambo = new SportsCar(8,255);
Car m5 = new SportsCar(10,240);
The following method call compiles fine:
lambo.getTopSpeed();
However this method call breaks with the error "cannot find symbol - method getTopSpeed()"
m5.getTopSpeed();
Now I understand that the getTopSpeed
method must exist in the base class in order for it to compile since m5
is a Car
type, so if I include getTopSpeed
in Car
then m5.getTopSpeed();
compiles nicely.
My questions are:
- Why does the error "cannot find symbol - method getTopSpeed()" happen at compile time and not run time?
- Why doesn't "late binding" prevent this error?
- Assuming
getTopSpeed
is implemented in Car
(so it compiles) when the program is run, does the compiler first check to see if getTopSpeed
exists in Car
and then checks to see if it is over-ridden in SportsCar
or does it just "know" that it is over-ridden already from the compiler and directly uses the over-ridden method?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…