• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism Concepts

 
robert stevens
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If class A has funA()
If class B extends A & has additional funB()
If class C extends A & has additional funB()

If i wanna have an array which stores objects of both class A and B
how do i do it....(assuming that i may wanna access funcB())
 
robert stevens
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sry for the typin mistake above.....
i want to store an array which holds objects of both class B and C
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

An instance of B IS-AN A, and an instance of C IS-AN A. So if the array holds elements of type A, there should be no problem in adding instances of B or C.

The trick is in using the array reference to access any methods defined in the subclass (for example, funB()). To do that, you will need to downcast the reference from type A to type B or C. But before you attempt the downcast, you should take some precautions to verify the true runtime type (B or C) -- otherwise, you will get a ClassCastException if the type is wrong.

Have you tried writing any code to experiment with this?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are certain you'll only deal with B & C ... create an interface HasFunB that defines funB() and make B and C implement that interface. Then you can make your array hold only HasFunB:

You won't even be able to put an instance of A in the array.

So, a) does that make sense and b) are you able to restrict what goes into the array that well?

If there's any chance an A could get into the array, go with Marc's suggestion for sure.
[ July 05, 2007: Message edited by: Stan James ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
If you are certain you'll only deal with B & C ... create an interface HasFunB that defines funB() and make B and C implement that interface. Then you can make your array hold only HasFunB...

The power of interfaces -- nice and clean!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic