Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 236
  • Last Modified:

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
0
nathanChun
Asked:
nathanChun
2 Solutions
 
shinobunCommented:
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
 
harshgroverCommented:
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now