implementing abstract methods in a concrete subclass
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   m_dunne
Posted On:   Tuesday, February 19, 2002 02:21 AM

Hi, I have a question about implementing an abstract method from an superclass in a concrete subclass. Currently I have an abstract class with an abstract with return type Map. In a concrete subclass of this I have implemented this method but want to return a HashMap. The reason that the abstract method is returning Map as opposed to HashMap is that all implementing subclasses are not restricted to returning a HashMap. (can also return a Hashtable). However, I thought this was possible, but it seems that it is not- as I am getting a compiler error. Does anyone know a way to do this. The superclass has to be an abstract class as opposed to an interface as   More>>
			
Hi,
I have a question about implementing an abstract method from an superclass
in a concrete subclass.

Currently I have an abstract class with an abstract with return type Map.

In a concrete subclass of this I have implemented this method but want to
return a HashMap. The reason that the abstract method is returning Map as
opposed to HashMap is that all implementing
subclasses are not restricted to returning a HashMap. (can also return a Hashtable).

However, I thought this was possible, but it seems that it is not- as I am
getting a compiler error.

Does anyone know a way to do this. The superclass has to be an abstract class
as opposed to an interface as there are a number of methods already implemented in it.

TIA
   <<Less

Re: implementing abstract methods in a concrete subclass

Posted By:   Paul_Connaughton  
Posted On:   Tuesday, February 19, 2002 03:08 AM

You can implement an overridden method to return a subclass of the return type, but you can not specify that inthe method header. The return type must be the same as the parent class.



The following example will allow you to return a HashMap as a Map, but you have to cast it to access HashMap functionality.




public class SomeSubclass extends AbstractClass{
public Map overRiddenMethod(){
HashMap map = new HashMap();
return map;
}
}
public static void main( String args[] ){
AbstractClass myClass = new SomeSubClass();
Map map = myClass.overRiddenMethod();
if ( map instanceof HashMap ){
//now you know that you have a HashMap
HashMap hashMap = (HashMap) map;
}
}
}

About | Sitemap | Contact