I am learning Java (slowly) from the ground up, but every now and again I peak at some “real” code and I found something that confused me.
The following line and ones like it:
JPanel panel = (JPanel) container.getContentPane();
My question is what is happening between (JPanel) and container.getContentPane()? Its not like they are being multiplied right?
I know this is a basic part of the language and as I continue learning I’ll get to this part, but I got really curious and wanted to know what it was right away. I didn’t really know what to google to get the answer.
No. It means “get this thing and treat it as a JPanel.” It’s called type casting and that syntax is used in C++, C# and many other languages.
You have to make sure that the way that the classes are related to each other allows for casting. For example, this wouldn’t work:
JPanelis aJComponentand so isJButton, butJButtondoes not descend fromJPanelthus you cannot cast between these objects. You can also cast from a child back to a parent, such as fromJSpinner.DefaultEditorback toJPanel, but not fromJPaneltoJSpinner.DefaultEditor.