S
S
Stanislav2016-10-22 22:55:05
Java
Stanislav, 2016-10-22 22:55:05

Don't all parent class methods use bridge methods when referring to an object of a child class?

Good afternoon. I read Horstmann's chapter on generics, it talked about how bridge methods work for generic methods.
(the Pair class is just a generic class with two fields of variable type)


class Datelnterval extends Pair<Date>
{
  public void setSecond(Date second){
    if (second.compareTo(getFirst()) >= 0)
      super.setSecond(second);
}
• • •
}
public static void main(String[] args){
  Datelnterval interval = new Datelnterval(. . .);
  Pair<Date> pair = interval; // допускается присваивание суперклассу
  pair.setSecond(aDate) ;
}

The setSecond() method call is assumed to be polymorphic, and therefore
the appropriate method is called. And since the variable pair refers
to an object of type DateInterval, it must be a call to DateInterval. setSecond().
But the fact is that type erasure interferes with the observance of the principle of polymorphism.
As a way out of this predicament, the compiler generates the following
bridge method in the DateInterval class:
public void setSecond(Object second) { setSecond((Date) second); }
To make this mechanism clearer, let's analyze the execution of the
following statement.
pair.setSecond(aDate
)
There is only one method named setSecond, namely setSecond(Object).
The virtual machine calls this method on the object referred to by
the pair variable. This object is of type DateInterval, and therefore
the DateInterval method is called. setSecond(Object). It is this method that is the synthesized
bridge method. After all, it, in turn, calls the DateInterval method.
setSecond (Date), which, in fact, is required.

I would like to know if, having a reference of the parent class to the object of the heir, where both are without class variables, the same procedure is not performed (obviously, it is not performed, since these very bridge methods are described in this chapter)?
I apologize if the question is put incorrectly, the operated structures seem quite confusing.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question