This may well be a stupid question, but here it goes anyway. In objective c, in an initiation method of a child class one often sets self=[super init]. Now, self is of the child class, and no conversion is required, which means (or not..) that the init method of the parent class somehow returns an object which actually belongs to the child class.
So my question is: can I define other methods or properties in a parent class, which when called from a child class return an object from the child class? There is something similar in Java called factory methods I think, so perhaps this question is not too outrageous..
Edit 1. Let me better explain what I mean: I know that I can find out in a ParentClass method, that I’m actually operating on an object from class ChildClass. This is by looking at [self class]. However, I would like to declare a method in ParentClass that returns an object from the child class, without knowing which class the child will be in advance. Better yet, I want the returned object to not even need formal conversion.
For example, I want a method in the parent class that does something like the following:
-(ChildClass *) partialCopyOfSelf {
//returns an object which is a partial copy of self (only copying properties that also
// exist in parent class, but such that applying [result class] will yield the child class
// and will require no further conversion
(ChildClass *) copy=[[ChildClass alloc] init];
//now copy stuff
return copy;
}
Now in the child class, I want to be able to implement something of the following sort:
-(MyClass *) copyOfSelf {
MyClass *copy=[super partialCopyOfSelf];
// now copy properties that only exist in my child class
return copy;
}
Edit 2 (from a comment I wrote to @wbyoung). The reason I want this is that at some point i may want to change the parent class’ properties from ivars to perhaps just computing some values for example, so a child would not know how to copy them correctly. I am writing this since someone may have a better idea of how to accomplish the same task.
The
initmethod is actually just working with the object that’s already been created of the child class. It’s the call toallocthat does this. That’s using the class to which you sent the message to figure out how to allocate the object.That being said, you can override methods in your child class. Messages are always sent to the object & method lookup starts at the top most class.
You could also do something like
[self class]to figure out your type in the parent class. That will only get you so far, though.[[self class] displayColor]would allow you to do something like implement a method & default class method implementation in the base class, but override a class method in subclasses as needed.