Re: Object casting (newbie)

From: VisionSet (spam_at_ntlworld.com)
Date: 12/20/03


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


Relevant Pages

  • Re: Generic ICloneable
    ... ICloneablethen the object should be an X and you can cast directly to ... public X Clone() {... ... If you had a generic IClonable interface, ... public class MyClass: IClonable ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Casting generic collections & inheritance
    ... public class B: A { ... >> convert (for Lists, at least from one type to another). ... > converter that can always do an identity conversion (i.e. convert from ... >> just a simple cast from Farmer to Person. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Inheritance Problem
    ... class without having to cast it every time. ... public class PokerTable: CardTable ... public PokerPlayer[] pokerplayers ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Casting of derived classes
    ... and cast it to the parent. ... is the Paint function - if you paint a button, ... function of both the button and the label class with the same line of code, ... >>> public class a { ...
    (microsoft.public.dotnet.languages.csharp)
  • Object casting (newbie)
    ... what happens if I cast my child object to the parent objects? ... If I cast a long to a byte I lose data. ... public class child1 extendes cParent{ ... public int getValue() { ...
    (comp.lang.java.programmer)