Declaring operator functions for specific subclasses

We already declared an operator function that allows any instance of Animal or its subclasses to use the postfix increment (++) operator. However, sometimes we want to specify a different behavior for one of the subclasses and its subclasses.

For example, we might want to express the age of dogs in the age value that is equivalent to humans. We can declare an operator function for the postfix increment (++) operator that receives a Dog instance as an argument and increments the age value 7 years instead of just one. The following lines show the code that achieves this goal. The code file for the sample is included in the swift_3_oop_chapter_04_14 folder:

    public postfix func ++ (dog: Dog) { 
      dog.age += 7 
    } 

The following lines create an instance of the SmoothFoxTerrier class named goofy, print the age for goofy, apply the postfix ++ operator, and print the new age. Because SmoothFoxTerrier is a subclass of Dog, Swift invokes the operator function that receives a Dog instance instead of invoking the one that receives an Animal instance as an argument. As a result of this, the operator function adds 7 to the age value instead of 1. The code file for the sample is included in the swift_3_oop_chapter_04_14 folder:

    var goofy = SmoothFoxTerrier(age: 7, name: "Goofy", 
    favoriteToy: "Scarf") 
    goofy.printAge() 
    goofy++ 
    goofy.printAge() 

Then, the following lines create an instance of the Cat class named garfield, print the age, apply the postfix ++ operator, and print the new age. In this case, garfield is a Cat instance, and Cat isn't a subclass of Dog. For this reason, Swift invokes the operator function that receives an Animal instance as an argument. Thus, the operator function just adds 1 to the age value. The code file for the sample is included in the swift_3_oop_chapter_04_15 folder:

    var garfield = Cat(age: 5, name: "Garfield", 
    favoriteToy: "Lassagna") 
    garfield.printAge() 
    garfield++ 
    garfield.printAge() 

The following lines show the results of the previous lines:

    Animal created 
    Mammal created 
    DomesticMammal created 
    Dog created 
    TerrierDog created 
    SmoothFoxTerrier created 
    I am 7 years old. 
    I am 14 years old. 
    Animal created 
    Mammal created 
    DomesticMammal created 
    Cat created 
    I am 5 years old. 
    I am 6 years old. 
..................Content has been hidden....................

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