Re: Java/C++ question
From: Chris Smith (cdsmith_at_twu.net)
Date: 01/23/05
- Next message: Andrew Thompson: "Re: accessing controls in a panel"
- Previous message: rjl444_at_hotmail.com: "Re: accessing controls in a panel"
- In reply to: dlukin_at_gmail.com: "Re: Java/C++ question"
- Next in thread: Andrew McDonagh: "Re: Java/C++ question"
- Reply: Andrew McDonagh: "Re: Java/C++ question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 22 Jan 2005 23:48:23 -0700
<dlukin@gmail.com> wrote:
> I'm not so much concerned with the commonality, but the differences -
> the extensions.
>
> Given:
> class A { public fooBar();}
> class B extends A {public fooBar(); public fooBar2();}
> class C extends A {public foobBar(); public fooBar3();}
>
> I have an array holding an instance of A, B, C. As I iterate across the
> array I want/need to be able to call different functions that each
> object implements.
Since the array contains three different kinds of object, how could you
possibly know which methods are there to call in the first place? Since
you don't know that fooBar2 exists, you can't possibly call fooBar2.
You can do this easily in neither C++ nor Java.
Now, if you know the specific set of subclasses, you can (in C++ or
Java) test to see which the object is, and cast appropriately. In Java:
for (int i = 0; i < array.length; i++)
{
if (array[i] instanceof C) ((C) array[i]).fooBar3();
else if (array[i] instanceof B) ((B) array[i]).fooBar2();
else array[i].fooBar();
}
The same can be done with RTTI in C++. That's generally a symptom of
poor design, though, in either language. The first question to ask is
why you didn't use polynorphism to achieve the same thing.
Java, in particular, can go even further with something called
reflection. Given the context, though, you almost certainly don't want
to do that.
> Implementing a common
> interface seems to give me access to the "commonality", but not the
> extensions...
If you explain how you expect to write code to use the "extensions",
then perhaps we could help. The toy code posted so far dodges the
issue. If you have NOT just created the object three lines earlier, and
therefore you don't know what the actual class of the object is, then
how what would the code look like?
The if statements in my example above are one option, and they work
fine. Is that what you're looking for, or something else?
-- www.designacourse.com The Easiest Way To Train Anyone... Anywhere. Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
- Next message: Andrew Thompson: "Re: accessing controls in a panel"
- Previous message: rjl444_at_hotmail.com: "Re: accessing controls in a panel"
- In reply to: dlukin_at_gmail.com: "Re: Java/C++ question"
- Next in thread: Andrew McDonagh: "Re: Java/C++ question"
- Reply: Andrew McDonagh: "Re: Java/C++ question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|