I'm starting to learn Objective-C watching YouTube lectures. In one of the lectures, the teacher said that whenever you try to call methods of an object that do not exist in its public API, the compiler will warn you, but will let you do it. In addition, if the method really exists, it would work at runtime.
An example to illustrate:
I have two classes: Vehicle and Ship. Vehicle implements the method move and ship is a child of Vehicle and implements shoot.
In the lecture, it was said that this code would compile (with a warning):
Ship *s = [[Ship alloc] init];
Vehicle *v = s;
[v shoot];
And this code would, in fact, work. Since v is actually a ship.
But what is happing in practice is that the compiler does not allow me to compile this code, because shoot does not exist in Vehicle public API.
The compiler error: No visible @interface for "Vehicle" declares the selector shoot
I really would like to know if the teacher was wrong or if I can change the compiler behavior. Could some help me? Thanks!
Obs.: I know I can do it using (id), I'm really trying to learn more about Objective-C behavior and syntax here
Classes:
vehicle.h:
@import Foundation;
@interface Vehicle : NSObject
- (void) move;
@end
vehicle.m:
#import "Vehicle.h"
@implementation Vehicle
- (void) move {
NSLog(@"moving");
}
@end
ship.h:
#import "Vehicle.h"
@interface Ship : Vehicle
- (void) shoot;
@end
ship.m:
#import "Ship.h"
@implementation Ship
- (void) shoot {
NSLog(@"shooting");
}
@end