Herencia y sobrescritura de métodos
Construya jerarquías de clases en Objective-C mediante herencia, sobrescriba métodos heredados y llame a la superclase usando super.
Herencia y sobrescritura de métodos es una lección gratuita de Objective-C iOS Development for Legacy & Enterprise Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Objective-C iOS Development for Legacy & Enterprise Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Objective-C iOS Development for Legacy & Enterprise Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What is Inheritance?
Inheritance lets a class reuse and extend another class. The new subclass gets all the methods and properties of its superclass, then adds or changes behavior.
Declaring a Subclass
The colon syntax in the interface declares the superclass. Here Dog inherits from Animal.
@interface Dog : Animal
- (void)fetch;
@endInherited Members
A subclass automatically has the superclass's public methods and properties — no need to redeclare them.
Dog *d = [[Dog alloc] init];
[d eat]; // inherited from Animal
[d fetch]; // defined on DogOverriding a Method
To change inherited behavior, redeclare a method with the same name in the subclass. This is overriding.
@implementation Dog
- (void)makeSound {
NSLog(@"Woof!");
}
@endCalling super
Use super to invoke the superclass version, extending rather than replacing its behavior.
- (void)makeSound {
[super makeSound];
NSLog(@"...and wags tail");
}Overriding init
Custom initializers almost always call [super init] first to set up inherited state, then add their own.
- (instancetype)init {
self = [super init];
if (self) {
_legs = 4;
}
return self;
}Polymorphism
A superclass-typed variable can hold any subclass instance. The correct overridden method runs at runtime — this is polymorphism.
Animal *pet = [[Dog alloc] init];
[pet makeSound]; // prints Woof!The instancetype Return
Initializers return instancetype, which adapts to the actual class being created — safer than hardcoding the type.
+ (instancetype)dogWithName:(NSString *)name;Checking Class at Runtime
Objective-C is dynamic. You can ask an object about its class.
if ([pet isKindOfClass:[Dog class]]) {
NSLog(@"It is a dog");
}NSObject the Root
Almost every class ultimately inherits from NSObject, which provides core behavior like alloc, init, isEqual:, and memory management hooks.
Designing Hierarchies
Favor shallow hierarchies. Use inheritance for genuine is-a relationships; for shared behavior across unrelated classes, prefer protocols and categories instead.
Quick Check
Test your inheritance knowledge.
Recap
You learned inheritance in Objective-C:
- Subclass with the
: Superclasssyntax - Inherited methods and properties come for free
- Override methods to change behavior
- Use
superto extend the parent version - Polymorphism picks the right method at runtime
Inheritance and polymorphism are pillars of OOP in Objective-C.
Preguntas frecuentes
¿La lección «Herencia y sobrescritura de métodos» es gratis?
Sí — el texto completo de «Herencia y sobrescritura de métodos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Objective-C iOS Development for Legacy & Enterprise Apps, actualiza a CoddyKit PRO. El curso de Objective-C iOS Development for Legacy & Enterprise Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Herencia y sobrescritura de métodos»?
Construya jerarquías de clases en Objective-C mediante herencia, sobrescriba métodos heredados y llame a la superclase usando super. Practicas Objective-C iOS Development for Legacy & Enterprise Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Objective-C iOS Development for Legacy & Enterprise Apps?
No se requiere experiencia previa. Objective-C iOS Development for Legacy & Enterprise Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Herencia y sobrescritura de métodos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Objective-C iOS Development for Legacy & Enterprise Apps?
Sí. Cada lección de Objective-C iOS Development for Legacy & Enterprise Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Clases, objetos y métodos
- Propiedades y variables de instancia
- Protocolos y categorías
- Herencia y sobrescritura de métodos