Doubt about getSource() instanceof

Asked

Viewed 38 times

0

Instanceof is a binary operator that tests whether an object is the subtype of a certain 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 don’t understand is why the return of the expression is true, since the return of the getSource() is an object type, so every object is a subtype of Jbutton? In case I have:

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

Assuming that the getSource() now return information about a Jlabel, as happens the differentiation since source is always the type Object? Instanceof will test the contents of source?

  • It’s called polimorfismo. And every object implicitly inherits from Object. Understanding polymorphism, answer your question

1 answer

1


This is called polymorphism. And every object implicitly inherits from Object. Understanding polymorphism, answers your question.

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

And when you do the check with instanceof jvm at runtime checks the class of the object being checked. (i.e., verifies which class was instantiated that object, whether it was instantiated as Jbutton, Jlist, etc.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.