views:

23

answers:

2

hi everyone,

i have a parent class called Course, and two child class PostgradCourse and UndergradCourse. i have a hashmap HashMap courses; i store all the postgradCourse and undergradCourse objects in the hashmap.

i want to retrieve an undergradCourse object from the hashmap using the key. Course course = courses.get(courseCode); then i want to call a method in the UndergradCourse class, setUnits() method course.setUnits(); but the compiler say cannot find symbol- method setUnit()

im pretty sure the problem is the compiler is looking for a method setUnit() in the Course class instead of UndergradCourse class

i did this but its not working UndergradCourse course = courses.get(courseCode); results in incompatible type

so how can i retrieve undergradCourse object from the hashmap as an undergradCourse object instead of course object? so then i can call a method inside the child class

thanks in advance

+1  A: 

The map stores two different types of course. When you retrieve a course from the map, you don't know which type of course you've retrieved.

To fix this, if you're programming in C++, there are at least three alternative ways to handle this:

  1. Have two different maps: one map of undergraduate courses, and another map of postgraduate cources (instead of a single map of base courses).
  2. When you get a base course from the single map, cast the object (using static_cast or dynamic_cast) to the type of subclass which you know/hope it is
  3. Declare the setUnit method as virtual (perhaps pure virtual) in the abstract base course, and give it two different implementations in the subclasses: then because it's declared in the base course, you can call it on the base course object which you retrieve from the map.
ChrisW
A: 

Assuming you program in Java, you can use the instanceof operator the determine whether the object is of a certain type.

Course course = courses.get(courseCode)
if(course instanceof UndergradCourse)
{
    UndergradCourse undergradCourse = (UndergradCourse)course;
    // do you stuff with the undergrad course
}

Note: Depending on the actual type of the object is breaking object oriented programing. It's not considered good style.

punytroll