Re: Object casting (newbie)
From: VisionSet (spam_at_ntlworld.com)
Date: 12/20/03
- Next message: bagbourne: "Re: Why doesn't Integer have a setValue(int i), and is there a way of changing its value."
- Previous message: Gerhald: "Object casting (newbie)"
- In reply to: Gerhald: "Object casting (newbie)"
- Next in thread: Anthony Borla: "Re: Object casting (newbie)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 20 Dec 2003 15:59:36 -0000
"Gerhald" <a1ring@nexus.hu> wrote in message
news:t_ZEb.152841$dt3.88571@news.chello.at...
> Hi,
>
> what happens if I cast my child object to the parent objects?
>
> If I cast a long to a byte I lose data. It's OK.
> If I use the casting below will this work, or give me back wrong values?
>
> ((cParent)myChild2).getValue();
>
> Thanks a lot!
>
> I have the following classes:
>
> public abstract class cParent{
> public abstract int getValue();
> }
> public class child1 extendes cParent{
> int a=5;
> int b=8;
> public int getValue() {
> return (a+b);
> }
> }
> public class child2 extendes cParent{
> int a=5;
> int b=8;
> int c=10;
> int d=15;
> public int getValue() {
> return (a+b+c+d);
> }
> }
Firstly I wouldn't use parent/child terminology that is more appropriate for
composition. Use super/sub.
But if myChild2 is an instance of child2 then:
((cParent)myChild2).getValue();
will evaluate to 38
the class a variable points to (ie the instance it was created under) is the
all important fact this governs the values of its attributes. The type (ie
its cast status if you like) merely controls visibility.
In you example myChild2 cannot have any other value than a+b+c+d = 38, but
the value evaluated by:
((cParent)myChild2).getValue();
is only possible because the getValue() method is visible due to the method
in the superclass (it matters not that it is abstract)'
-- Mike W
- Next message: bagbourne: "Re: Why doesn't Integer have a setValue(int i), and is there a way of changing its value."
- Previous message: Gerhald: "Object casting (newbie)"
- In reply to: Gerhald: "Object casting (newbie)"
- Next in thread: Anthony Borla: "Re: Object casting (newbie)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|