Doubt about getSource () instanceof

0

Instanceof is a binary operator that tests whether an object is the subtype of a given type. Ex:

Object fonte = e.getSource();
if (fonte instanceof JButton){
...
}

If getSource () returned information from a JButton the result of the expression will be true .

What I do not understand is why the return of the expression is true, since the return of getSource () is an object type, so every object is a JButton subtype If I have:

Object fonte = e.getSource();
if (fonte instanceof JLabel){
...
}

Assuming that getSource () now returns information about a JLabel , how differentiation happens since source is always of type Object ? Instanceof will test the content of source ?

    
asked by anonymous 09.12.2015 / 15:18

1 answer

1

This is called polymorphism. And every object implicitly inherits from Object. Understanding polymorphism, he'd answered his question.

Not going into detail about polymorphism, as we already know that every object inherits from Object, then by polymorphism an object of type Object can receive (save reference) from any other object, and that is what is happening.

And when you do the check with instanceof the jvm at runtime checks the class of the object being checked. (ie it checks which class was instantiated this object if it was instantiated as JButton, JList, etc. .)

    
09.12.2015 / 15:36