Reputation: 1921
I am new to Objective-C and want to know about inheritance. I am aware of the concepts but confused with the methods that programmer uses to inherit a class.
I have two classes: class A and class B, and want to make B a child of A.
Sometimes a programmer uses #import "class A"
and sometimes uses the @
sign. Which one of them should be used, and why? Is there any difference between their uses?
Another question I have is about the ":
" sign which we write after class declaration, for example @interface class_A : class_name
In past I was a student of Java and C#, and their inheritance is similar to each other. But is Objective-C (I am currently working for iPhone) the same?
Upvotes: 3
Views: 2950
Reputation: 189
if we do this
@interface Class_B : Class_A
mean we are inheriting the Class_A into Class_B, in Class_B we can access all the variables of class_A.
if we are doing this
#import ....
@class Class_A
@interface Class_B
here we saying that we are using the Class_A in our program, but if we want to use the Class_A variables in Class_B we have to #import Class_A in .m file(make a object and use it's function and variables).
Upvotes: 0
Reputation: 95462
There is a difference between those terms, and I can see where your confusion is.
The #import
is used to load definitions of a class's h file. This is, in a way, similar to C#'s using
keyword, but in Objective-C we need to specify everything in the class level, not in the namespace level -- there's no concept of namespace level encapsulation in Objective-C.
The @class
keyword is used whenever you need to declare that an object is valid -- but if you're going to use the internals of that object you will eventually need to add an #import
of the class anyway. There's a great answer here on the difference between @class and #import.
As with C# and Java, inheritance is achieved by using the : operator in your h file. So in your declaration of Class B, it should go like:
@interface Class_B : Class_A
Hope this clears everything up.
update for your comment:
Let's say I want to inherit class A into class B, and use class C as a variable somewhere. You'll need the ff to make it work:
#import "Class_A.h"
@class Class_C;
@interface Class_B : Class_A {
Class_C *myvariable
}
Now, lets say somewhere inside your file you need to access a Class_C member e.g., myvariable.Property1
, that's the time you turn @class Class_C
into #import "Class_C.h"
.
I don't think declaring it like this:
@class Class_A;
@interface Class_B : Class_A
would work... you'll still need an #import "Class_A.h"
somewhere which makes the @class
declaration somewhat redundant.
Upvotes: 4