java - How was one method chosen over another in this code? -


This is one of those SCJP questions. The code below gives the code alpha: fubeta: fubeta: barbeta: bar , and I do not know why first fu call chose alpha foo rather than beta if the alpha.foo parameter is stringed Instead of string ..., then the output is beta: fubeta: fubeta: barbeta: bar that makes sense.

My understanding is that when you say that alpha a = new beta (); , Compiler check for alpha. Foo, but JVM will actually be beta. Fu For one thing, beta has a fu method whose signature matches the call. For the second, I thought that the ways of classgear are only run when there is no other way available which matches the call. So two reasons I think Alpha.foo should not be run. What part of this understanding is wrong?

Thank you!

  square alpha {public void foo (string ... args) {// If this was string arguments, then it is understood System.out.print ("alpha: foo") ; } Public Zero Times (string A) {System.out.print ("alpha: bar"); }} Public class beta alpha {public void foo (string A) {System.out.print ("beta: af") extends; } Public Zero Times (String A) {System.out.print ("Beta: Bar"); } Public static zero main (string [] arg) {Alpha A = new beta (); Beta B = (beta) A; A.foo ("exam"); // deceptive line b.foo ("test"); A.bar ("test"); B.bar ("test"); }}  

EDIT: I think I know where I now understood things wrong? I think a superclass sc = new subclass (); In the situation, whatever method is called on SC, they will be searched in subclass at runtime, although they will be searched in superclass at compile time. It is revealed, as I now feel, that I understand that whatever method is called on SC, both will be searched in superclasses in compile time and run-time, sub - The method is not provided "better" version of the method, hereafter, at compile-time, the compiler will know that there is a way to implement the subclass version.

The method overloading is compiled-time, on method override-on the runtime.

In your case, foo does not override beta in alpha FU it overloads it with various arguments ( You can prove it by adding an annotation to the @override which is a best practice to detect such obvious potential problems).

Another point here secretly is that you refer to alpha # fu (.. from the context of beta - i.e. b.foo ("test"). ) will always invoke the non-varargs method why this happens,


Comments