Defining a Class
Much of object-oriented programming consists of writing the code for new objects—defining new classes. In Objective-C, classes are defined in two parts:
- An interface that declares the methods and instance variables of the class and names its superclass
- An implementation that actually defines the class (contains the code that implements its methods)
Class Interface
The declaration of a class interface begins with the compiler directive @interface
and ends with the directive @end
. (All Objective-C directives to the compiler begin with “@”.)
@interface ClassName : ItsSuperclass |
{ |
instance variable declarations |
} |
method declarations |
@end |
Methods for the class are declared next, after the braces enclosing instance variables and before the end of the class declaration. The names of methods that can be used by class objects, class methods, are preceded by a plus sign:
The methods that instances of a class can use, instance methods, are marked with a minus sign:
- (void)display;
If a return or argument type isn’t explicitly declared, it’s assumed to be the default type for methods and messages—an id
. The alloc
method illustrated earlier returns id
.
When there’s more than one argument, the arguments are declared within the method name after the colons. Arguments break the name apart in the declaration, just as in a message. For example:
- (void)setWidth:(float)width height:(float)height;
No comments:
Post a Comment