How to access an abstract method

nathanChun
nathanChun used Ask the Experts™
on
Dear Expert:

I'm new to java.

I have an abstract class A, with an abstract method "calculate()".
I extend from A, classes B, C, and D.  The all implement "calculate()" differently.
I then put these classes as values into a MAP.
When I try to access the calculate() method using the .get method of the MAP,  the compiler says that there is not calculate() method.    "foo.get("add").calculate()"

How do I polymorphically get at the calculate method?

Any simple examples out there?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
By default, Map#get() will return Objects.

For java 5, you can use generics:

Map<String, A> foo = new HashMap<String, A>();
foo.put("add", new B());
foo.get("add").calculate();

Java 1.4 and before, you need to cast it to A:

((A) foo.get("add")).calculate();

Author

Commented:
Casting it to the base class will get met acess to the abstract method calculate?
yes that would be the right way to do it. U can cast it to the parent class, and you would be able to access the method. this is one of the most oft used principles in factory loading...

Gary

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial