Let's consider two classes, super and sup extending super:
Class SuperClass{
int superDataMember;
}
Class SubClass extends SuperClass{
int subDataMember;
}
I need to have another CompositeClass
class that may use super or sub composition depending on some criteria. My question is: Should I use
An instance of
SuperClass
insideCompositeClass
- Thus, I can use either
SuperClass
instance orSubClass
instance. - But how will methods accessing
subDataMember
behave if the accessed instance is ofSuperClass
? Maybe an
instanceOf
check may work at the beginning of each method?Class CompositeClass {
private SuperClass sc;
public getSuperDataMember () {// some code}
public getSubDataMember () {
if (this.sc instanceOf SubClass)
// some code
}
}
- Thus, I can use either
An instance of
SubClass
insideCompositeClass
Thus, I will lose the ability to access
SuperClass
instances!Class CompositeClass {
private SubClass sc;
public getSuperDataMember () {// some code}
public getSubDataMember () {// some code
}
}
Implement two versions of
CompositeClass
, the first isSuperCompositeClass
with an instance ofSuperClass
and the secondSubCompositeClass
that extends the first with an instance ofSubClass
!
Aucun commentaire:
Enregistrer un commentaire