Reputation: 31560
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.
Upvotes: 1
Views: 155
Reputation: 160191
It's a cast expression (see JLS 15.16, Cast Expressions).
It means "treat the results of the getContentPane()
call as a JPanel
".
Casts can fail, causing a ClassCastException
(see JLS 5.5, Casting Conversion).
Upvotes: 1
Reputation: 37506
Its not like they are being multiplied right?
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:
JPanel p = new JPanel();
JComponent c = (JComponent)p;
JButton b = (JButton)c;
JPanel
is a JComponent
and so is JButton
, but JButton
does not descend from JPanel
thus you cannot cast between these objects. You can also cast from a child back to a parent, such as from JSpinner.DefaultEditor
back to JPanel
, but not from JPanel
to JSpinner.DefaultEditor
.
Upvotes: 5
Reputation: 14053
This is called a type cast. The method getContentPane()
normally return a Container, but we want to get it in a JPanel so we'll be able to use JPanel methods. Of course the two types have to be compatible (JPanel is a specific implementation of Container (through JComponent) for example)
Upvotes: 1
Reputation: 633
Yes this is how type casting is made in java. As you know java works with references. In your case you have a JPanel type reference and container.getContentPane() returns (correct me if I am wrong my Swing is a bit rusty) container, so since those two are incompatible you need to type cast to make them compatible. Hope that helps
Upvotes: 0