The Artima Developer Community
Sponsored Link

Java Answers Forum
Upcasting

2 replies on 1 page. Most recent reply: Jul 7, 2005 2:12 AM by Antonio

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Ashish

Posts: 1
Nickname: bassi
Registered: May, 2005

Upcasting Posted: May 12, 2005 2:41 AM
Reply to this message Reply
Advertisement
I am unable to understand whats the use of upcasting, what do we achieve by upcasting that we cant do normally.


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Upcasting Posted: May 12, 2005 6:12 AM
Reply to this message Reply
Upcasting spares some work.

Example: a JPanel contains some JLabels and some JTextfield and is set up with a null layout.

We want to move all elements to the right.

If the objects would be stored as JLabel and JTextfield, we would have to write 2 different loops: one handling the JLabels, the other handling the JTextFields.

But since both extend the class Component and this class offers all needed methods, we cast them to Component, so we only need one operation with one loop.


You will never write like
doSomethingWith((Component)myJFrame);

The upcasting is done by the compiler.

Antonio

Posts: 33
Nickname: arhak
Registered: Jul, 2005

Re: Upcasting Posted: Jul 7, 2005 2:12 AM
Reply to this message Reply
In fact yes
You could be interested in writting
doSomethingWith((Component)myJFrame);

because you might have two different methods
void doSomethingWith(Component c) {...}
void doSomethingWith(JFrame f) {...}
and (for some extravagant reason) you might want to invoke the first one with a JFrame as argument but the compiler will choose the second one by default (nearest match) so you must cast your JFrame to Component

Flat View: This topic has 2 replies on 1 page
Topic: Applet to Applet Communication Previous Topic   Next Topic Topic: Converting BufferedImage bit-depth

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use