How to access an abstract method

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
nathanChunAsked:
Who is Participating?
 
shinobunConnect With a Mentor 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();
0
 
nathanChunAuthor Commented:
Casting it to the base class will get met acess to the abstract method calculate?
0
 
harshgroverConnect With a Mentor Commented:
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
0
All Courses

From novice to tech pro — start learning today.