So I'm having a bit of trouble understanding this example that was shown in class -- it's supposed to illustrate subtleties between static & dynamic types in Java.
public class Piece {
public static void main (String[] args) {
Piece p2 = new Knight();
Knight p1 = new Knight();
p1.capture(p2); // call 1; "Knight is bored" is supposed to be printed
p2.capture(p1); // call 2; "knight is bored" is supposed to be printed
}
public void capture () {
System.out.println("Capturing");
}
public void capture (Piece p) {
System.out.println("I'm bored")
}
public class Knight extends Piece {
public void capture (Piece p) {
System.out.println("Knight is bored");
}
public void capture (Knight k) {
System.out.println("TOO SLOW BUDDY");
}
}
Here's my understanding of what happens when the two calls get made:
Call 1: p1.capture(p2)
The capture method is called from p1. Via dynamic type lookup, it sees that p1's dynamic type is Knight. So it looks in the Knight subclass. p2 is passed in as an argument. To see which capture method to invoke within the Knight subclass, it checks the static type of p2, which is piece. Therefore, "Knight is Bored" is printed. This is the right output, but is my reasoning correct?
Call 2: p2.capture(p1)
Using the same reasoning, the capture method is called from p2. Via dynamic type lookup, it sees that p2's dynamic type is Knight. So it looks in the Knight subclass. p1 is passed in as an argument. To see which capture method to invoke, it looks at p1's static type, which is Knight. Therefore, "TOO SLOW BUDDY" is printed. Obviously, my reasoning is wrong, as that's not what's really printed. Any direction?
Thanks!
In the second call, you can only call methods of the Piece class or the same methods in its subclasses. That's why it will call capture(Piece p) instead of capture(Knight k). The latter is specific to the Knight class.
For example, when we have "List a = new Arraylist();", you can only call methods that were declared in List, not additional but similar looking methods in ArrayList.
p2.capture(p1); // call 2; "knight is bored" is supposed to be printed
Here you are calling capture method on Piece class object and since you have passes p1(Knight) class reference it will call overridden capture method of class Knight. that is
public void capture (Piece p) {
System.out.println("Knight is bored");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With