0

I was reading Core Java Volume I and I encounter a question in translating generic expression. Here is what the book said.

enter image description here

I don't understand why there is a interfere. For the highlighted sentence, why setSecond(Object) method is called? Shouldn't it be setSecond(Date) method since interval is a DateInterval object?

user5574376
  • 371
  • 1
  • 5
  • 12
  • *"Type erasure interferes with polymorphism"* ... just as *"inheritance breaks encapsulation"*. These are well described systems, however, and these inconvenient facts are not an impediment to those who know how to work with them. – scottb Jun 02 '16 at 04:28
  • The example in that book is pretty confusing. I don't even see how it illustrates the point, honestly. Look at the example under "Why else is it needed?" here: http://stackoverflow.com/questions/5007357/java-generics-bridge-method – johncip Jun 02 '16 at 04:35

1 Answers1

0

The main problem, I think, is that all that comes between brackets (in this case ) only exists when you're writing the code. It's a compilation-time checking. That's what the type erasure is all about. When you compile the code, all you have are references to Object and these bridge methods in the bytecodes.

Leo
  • 751
  • 4
  • 29
  • Yes, I understand that, but the book states the setSecond method in DateInterval class after erasure is still setSecond(Date), so shouldn't it invoke that method for a DateInterval object instead of setSecond(Object)? – user5574376 Jun 02 '16 at 04:04
  • No, because pair was declared as Pair (which is the superclass that only contains setSecond(Object)), even being assigned to a DateInterval (the subclass that has the setSecond(Date)) – Leo Jun 02 '16 at 04:07
  • Well, I am still a little confused. So this is the reason why it interfere with polymorphism?I thought dynamic binding will choose setSecond(Date) since interval is a DateInterval. Am I thinking something wrong? – user5574376 Jun 02 '16 at 04:13
  • You're not wrong. It must call setSecond(Date), but the problem is that there's no setSecond(Date) in the superclass, only setSecond(Object), so the compiler creates this bridge method to make the subclass actually inherit setSecond(Object), but acting just like a proxy to call the right method, which is setSecond(Date) – Leo Jun 02 '16 at 04:35
  • Sorry, I am still a little lost. So are u saying aDate in the example is an instance of Object class? – user5574376 Jun 02 '16 at 05:12
  • 1
    I think you have to read the book again and ask yourself why the compiler has to create a bridge method :-) the bridge method is the consequence of why type erasure offends polymorfism :-) – Leo Jun 02 '16 at 05:26