I'm having a hard time wrapping my head around this concept. I'll take the quote exactly from the book:
Class objects also inherit from the classes above them in the hierarchy. But because they don’t have instance variables (only instances do), they inherit only methods.
Correct me if I'm wrong, but a class object would be this:
NSString *aString = [[NSString alloc]initWithString:@"abc.."];
The class object in this case is *aString
-- am I correct so far?
The thing that confuses me is the second sentence in the quote above, "But because they don’t have instance variables (only instances do), they inherit only methods."
I thought that an object (in this case *aString
) was the instance of the NSString
class.
The second sentence above is implying that an instance is something different. It's not making any sense to me.
You are incorrect.
NSString *aString = [[NSString alloc] initWithString:@"abc..."];
In this line, we have, from left-to-right:
NSString *
aString
Class
: NSString
+alloc
-initWithString:
@"abc..."
In Objective-C, a Class
is actually a kind of object. You can interact with them in many of the same ways that you can instances, but since they are "classes", they cannot have instance variables (since instance variables, by definition, are only for instances). Classes
only have methods. They inherit from other Classes
, and this is how object inheritance is implemented.
For more information on this, check out this awesome blog post by Greg Parker: http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With