Overriding a superclass method

So far, we just used multiple print() statements to display the values of the class instance. Instead of using multiple print() statements, we will implement a description() method to display all of the instance properties in the Debug area:

  1. Modify your class declaration to implement a description() method, as shown:
// Classes
// Creating a class declaration
class Animal {
var name: String
var sound: String
var numberOfLegs: Int
var breathesOxygen: Bool = true

// Class initializer
init(name: String, sound: String, numberOfLegs: Int,
breathesOxygen: Bool) {
self.name = name
self.sound = sound
self.numberOfLegs = numberOfLegs
self.breathesOxygen = breathesOxygen
}

func makeSound() {
print(self.sound)
}

func description() -> String{
return("name: (self.name) sound: (self.sound)
numberOfLegs: (self.numberOfLegs) breathesOxygen:
(self.breathesOxygen)")
}
}
  1. Modify the rest of your code, as shown, and run the program:
// Making an instance of the class
let cat = Mammal(name: "Cat", sound: "Mew", numberOfLegs: 4,
breathesOxygen: true)

// Printing out the property values
print(cat.description())

// Calling an instance method
cat.makeSound()

You will see the following in the Debug area:

name: Cat sound: Mew numberOfLegs: 4 breathesOxygen: true
Mew
true

As you can see, even though the description() method is not implemented in the Mammal class, it is implemented in the Animal class. This means it will be inherited by the Mammal class, and the instance properties are printed to the Debug area.

Note that hasFurOrHair is missing, and we can't put it in because hasFurOrHair is not a property for the Animal class. We can, however, change the implementation in the subclass, so that the hasFurOrHair value is displayed.

  1. Add the following code to your Mammal class declaration and run it:
// Mammal class, subclass of Animal
class Mammal: Animal {
let hasFurOrHair: Bool = true

// overrides the description method in the superclass
override func description() -> String {
return("Class: Mammal name: (self.name) sound:
(self.sound) numberOfLegs: (self.numberOfLegs)
breathesOxygen: (self.breathesOxygen) hasFurOrHair:
(self.hasFurOrHair) ") }
}

The override keyword is used here to specify that the description method declared here is to be used in place of the superclass implementation. You will see the following in the Debug area:

Class: Mammal name: Cat sound: Mew numberOfLegs: 4  
breathesOxygen: true hasFurOrHair: true
Mew
true

hasFurOrHair is displayed in the Debug area, showing that we are using the subclass implementation of the description() method, instead of the class implementation.

You've created a class declaration and implemented your first instance of a class! Cool! Let's look at structures next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.154.139