Solved

How to access an abstract method

Posted on 2006-10-20
3
210 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
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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 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