Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Class Inheritance

I have a super class: SuperClass (for simplicity).

I also have 2 classes that sublcass this SuperClass: SubclassA and SubclassB.

Assuming I have the following method:

....
public SuperClass getObj(String name, Date create){
SuperClass obj;

if(name == "blah"){
return obj = new SubclassA();
}

//if create date after some other date
if(create.After(new Date(1232341324) ){
return obj = new SubclassB();
}

//else
return obj = new SuperClass();
}
....

Based on this, will all the objects ONLY be SuperClass objects and only available to use SuperClass methods, etc?
Or, if the first or second if statement is executed, the returned object from this method will have access to the methods defined in the subclass?

Thanks!
[966 byte] By [pacify] at [2007-11-11 10:08:15]
# 1 Re: Class Inheritance
You're attempting to traverse in the wrong direction on a class hierarchy. Derived (sub) classes are instances of the base (parent or super) class, but the parent cannot be an object of the derived class.

You can address an object of the derived class as a parent object, but not vice-versa.

So, in answer to your questions, the SuperClass objects will only be able to use SuperClass methods ... a SuperClass object will only look in the method table for the SuperClass and does not have access to the method table (virtual table/Class Instance Record) for a SubClass: therefore, it has no access to the fields and methods of the SubClass.

You are attempting to create a system which is addressed by the "Strategy" Design Pattern ... research this to modify your design.
nspils at 2007-11-11 22:31:56 >