Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

polymorphism - Calling method from java child class not in parent class

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:

  1. Why does the error "cannot find symbol - method getTopSpeed()" happen at compile time and not run time?
  2. Why doesn't "late binding" prevent this error?
  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Java is statically typed language, so a variable type should be known at compile time. If type that is known to the compiler doesn't expose such a method - it is compilation failure. Exactly for the reason to not let it to runtime.

  2. Why should it? It just finds the method body late, not signature. Still, static typing means that signature must be satisfied at compile time.

  3. At runtime JVM tries to find the most specific implementation. In SportsCar, in your case. If it is inherited from parent but absent in child - parent's code is used.

If you need to call method from specific child which is absent in variable type - you can cast it at runtime at your own risk of getting ClassCastException.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...