This is another SCJP question. The code below prints Alpha:fooBeta:fooBeta:barBeta:bar , and I don't understand why the first call to foo chose Alpha foo instead of the beta. If the Alpha.foo parameter is changed to String instead of String ..., then the output will be Beta:fooBeta:fooBeta:barBeta:bar , which makes sense.
I understand that when you say Alpha a = new Beta(); , the compiler checks Alpha.foo, but the JVM actually launches Beta.foo. First, Beta has a foo method whose signature matches the call. For another, I thought that varargs methods only execute when there is no other method available that matches the call. Therefore, for two reasons, I believe that Alpha.foo should not start. What part of this understanding is wrong?
Thanks!
class Alpha { public void foo(String... args) {
Edit: I think I know where I misunderstood right now. I thought in a situation SuperClass sc = new SubClass(); any method that is called in sc will search in SubClass at run time, although at compile time they will be executed in SuperClass. It turns out, as I now think, I understand that any method called sc will look in SuperClass both at compile time and at runtime, UNLESS SubClass has provided a "better" version of the method. Then, even during compilation, the compiler will know that the method to call is the version of SubClass.
java inheritance polymorphism
Bad request
source share