Reputation: 944
There is the following structure
My own classes
class HERMEntityRelationshipType
class HERMEntityType extends HERMEntityRelationshipType
class HERMRelationshipType extends HERMEntityRelationshipType
Classes generatetd from a framework.
class DBMEntityRelationshipType extends DBMDataObject
class DBMEntityType extends DBMDataObject
class DBMRelationshipType extends DBMDataObject
I wrote two similar methods.
private HERMEntityType parseERType(DBMEntityType dbmEntityType) {...}
private HERMRelationshipType parseERType(DBMRelationshipType dbmRelationshipType){...}
But I would like to just have one method like this:
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){...}
But after calling that general method I am not able to cast my classes to a subclass: e.g.HERMEntityRelationshipType
to HERMEntityType
. But casting DBMDataObject
to DBMEntityRelationshipType
works fine. So they must implement these classes smarter then me. My cast looks like this:
HERMEntityType entityType = (HERMEntityType) parseERType((DBMEntityRelationshipType) dataobject);
and results in: Exception in thread "main" java.lang.ClassCastException: hermtransformation.herm.HERMEntityRelationshipType cannot be cast to hermtransformation.herm.HERMEntityType
.
So what is required to cast my superclass to a subclass?
Upvotes: 1
Views: 67
Reputation: 3907
the problem here is that Java does not allow downcasting. You should create new Objects of the childclasses instead of returning new Objects of the parent class.
The parseERType Method should look something like this:
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){
if(dbmERType.getClass().equals(DBMEntityType.class)) {
return new HERMEntityType(dbmERType);
} else {
return new HERMRelationshipType(dbmERType);
}
}
Upvotes: 2
Reputation: 26
There seems to be no relation between DBMEntityRelationshipType and HERMEntityType. As per your input model, the relation between DBMDataObject and HERMEntityRelationshipType is missing. Ideally, if DBMEntityRelationshipType extends from HERMEntityRelationshipType also, then this cast would work. Moreover, you would need to cast to parent reference to project polymorphism.
Upvotes: 0