Solved

How to access an abstract method

Posted on 2006-10-20
3
222 Views
Last Modified: 2010-03-31
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
Comment
Question by:nathanChun
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 9

Accepted Solution

by:
shinobun earned 400 total points
ID: 17777414
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
 

Author Comment

by:nathanChun
ID: 17777862
Casting it to the base class will get met acess to the abstract method calculate?
0
 
LVL 2

Assisted Solution

by:harshgrover
harshgrover earned 100 total points
ID: 17777946
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question