Question

Given the line below where Square is a subclass of Rectangle:

Rectangle *thisObject = [[Square alloc] init];

thisObject contains: 1. All the instance variables of a Square object. 2. All the instance methods implemented in the Square object. 3. All the instance variables of a Rectangle object. 4. All the instance methods implemented in the Rectangle object.

Given the line below where Square is a subclass of Rectangle:

Square *thisObject = [[Square alloc] init];

thisObject contains: 1. All the instance variables of a Square object. 2. All the instance methods implemented in the Square object. 3. All the instance methods implemented in the Rectangle object.

Any disagreements?

Was it helpful?

Solution

I disagree. You missed that the second also contains all the instance variables of a Rectangle object.

Both instances are exactly the same. Instances are, with the exception of things like class clusters, what you alloc them as, not what you later claim them to be.

Both of those instances are of Square objects.

The line:

Monkey *george = [[Square alloc] init];

does not do anything to make george a Monkey. He's a Square. The compiler will warn you if you send him messages that Monkey doesn't respond to, but if they're Square messages (or any superclass of Square), he'll respond as a Square.

And if you send george Monkey messages, you'll get runtime errors about selector not found. Unless your Monkey message just happens to match a Square message (which will happen with methods in their common superclasses).

That's polymorphism. You can claim george is a Monkey, or a Circle, or just an id, but he'll respond as what he is, a Square.

OTHER TIPS

No, these are identical. The only difference between the two is that you will get a warning from the compiler if you tried to send a Square message to the thisObject typed as a Rectangle. But this will only be a warning, the message send would actually work at runtime.

You're correct. The type of the pointer doesn't matter for the type of the object itself. It just makes it easier for the compiler to check the types. You could also use id for all of your objects and their behavior wouldn't change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top