I'm learning to do class inheritance, and there's something I don't understand. First, I show you the code.
class Persona {
var edad : Int
var nombre : String
var telefono : Int
init(edad: Int, nombre: String, telefono: Int) {
self.edad = 0
self.nombre = nombre
self.telefono = 123456789
}
}
class Cliente: Persona {
var credito : Int
init(credito: Int) {
self.credito = 0
super.init(edad: <Int>, nombre: <String>, telefono: <Int>)
}
}
Well, when I write el in the subclass super.init
, Xcode warns me that I have to give it the parameters, which I would like to give them when creating an object of the subclass. If I try to create:
var unCliente = Cliente(credito: Int)
it only lets me give it the credit parameter and not the parameters of the parent class Person.
So my question is this: should I give it the parameters when creating the subclass? Is it possible to do what I try?
In
init
the classPersona
, unless you want to have a default value created with that data or you can change it to:When you create an object of type
Cliente
and want to initialize the super class, you must add the parameters in the oneinit
of the child class:Now let's see how it works:
We create an object of type array of
Personas
:We create two objects of type
Cliente
:Since client inherits from person, we can add the clients to the person array because you already initialized the super class in the
init
child class:If you print the names of both the objects of
Persona
andCliente
you can check that they are the same:If you don't want to have the
init
in Person, you can add the values of the super class at the time you initialize it in the child class.You can call those attributes from the child class after initializing the super class with:
Thus the child class:
The result is the same as in number 4. above.