Swift Learning Swift Programming Journey---Inheritance (17)

Source: Internet
Author: User
Tags class definition



In Swift, inheritance is a basic feature of distinguishing between "class" and other types. Swift does not support multiple inheritance. Classes can invoke and access superclass methods, properties and subscripts subscript, and can override (override) These methods, properties, and subordinate scripts to optimize or modify their behavior. Swift checks to see if your rewrite definition has a matching definition in the superclass to ensure that your rewrite behavior is correct.


Property observer can be added to attributes inherited from a class so that when the property value changes, the class is notified. You can add a property observer for any property, whether it was originally defined as a stored-type property (stored) or a computed property (computed).





  Definition of a base class



Classes that do not inherit from other classes, called base classes (base CALSS)


Note: Classes in Swift are not inherited from a common base class. If you do not specify a superclass for the class you define, the class automatically becomes the base class. The following example defines a base class called vehicle. This base class declares two properties (Numberofwheels and maxpassengers) that are common to all vehicles. These properties are used in the description method, which returns a string-type description of the vehicle's characteristics.

class Vehicle {
    var numberOfWheels: Int
    var maxPassengers: Int
    func description ()-> String {
        return "\ (numberOfWheels) wheels; up to \ (maxPassengers) passengers"
    }
    init () {
        numberOfWheels = 0
        maxPassengers = 1
    }
}
  Subclassing Subclassing is the subclass inherits the characteristics of superclass, and can optimize or change it. You can also add new features to subclasses. To indicate the superclass of a class, write the superclass name after the subclass name, separated by a colon:
class SomeClass: SomeSuperclass {
    // Class definition
}
 

In the next example, define a more specific vehicle class called Bicycle. This new class is created on the basis of the Vehicle class. So you need to put the Vehicle class after the Bicycle class, separated by a colon.
class Bicycle: Vehicle {
    init () {
        super.init ()
        numberOfWheels = 2
    }
}
Bicycle is a subclass of Vehicle, and Vehicle is a superclass of Bicycle. The new Bicycle class automatically obtains the features of the Vehicle class, such as the maxPassengers and numberOfWheels attributes. You can customize these features in subclasses, or add new features to better describe the Bicycle class. The Bicycle class defines a constructor to set its custom characteristics (the bicycle has only 2 wheels). Bicycle's constructor calls the super.init () constructor of its parent class Vehicle to ensure that the Vehicle class has initialized them before the Bicycle class attempts to modify those inherited properties. Note: Unlike Objective-C, in Swift, initializers are not inherited by default. The default value of maxPassengers in the Vehicle class is already correct for the bicycle, so it has not been changed in the Bicycle constructor. The original value of numberOfWheels is incorrect for the bicycle, so change it to 2 in the initializer. Bicycle can not only inherit the properties of Vehicle, but also inherit its methods. If you create an instance of the Bicycle class, you can call the description method it inherits, and you can see that the attribute value it has output has changed:
let bicycle = Bicycle ()
println ("Bicycle: \ (bicycle.description ())")
// Bicycle: 2 wheels; up to 1 passengers
 Subclasses can continue to be inherited by other classes:

class Tandem: Bicycle {
    init () {
        super.init ()
        maxPassengers = 2
    }
}
Note: Subclasses are only allowed to modify the variable attributes inherited from the superclass, but cannot modify the inherited constant attributes.

 

Overriding

Subclasses can provide their own implementation for inherited instance methods, class methods, instance properties, or subscripts. We call this behavior overriding. Use the override keyword to achieve. Unexpected rewrite behavior may cause unpredictable errors. Any rewrite lacking the override keyword will be checked for errors at compile time. The override keyword reminds the Swift compiler to check whether the superclass (or one of the superclasses) of this class has a declaration that matches the rewritten version. This check can ensure that your rewrite definition is correct. Access superclass methods and attributes Use super to access superclass attributes, methods, and subscripts. In the rewrite implementation of method someMethod, you can call superMethod someMethod by super.someMethod () In the rewrite implementation of the getter or setter of the property someProperty, you can access the superclass version of someProperty property through super.someProperty. In the rewriting implementation of the attached script, the same subscript in the superclass version can be accessed through super [someIndex]. 1. Rewrite method
class Car: Vehicle {
    var speed: Double = 0.0
    init () {
        super.init ()
        maxPassengers = 5
        numberOfWheels = 4
    }
    override func description ()-> String {
        return super.description () + ";"
            + "traveling at \ (speed) mph"
    }
}
 

Car declares a new storage attribute speed, which is of type Double, and the default value is 0.0, which means "speed is 0 miles per hour." Car has its own initializer, which sets the maximum number of passengers to 5 and the number of wheels to 4. Car rewrites the inherited description method, its declaration is consistent with the description method in Vehicle, and the override keyword is added in front of the declaration. The description method in Car is not completely customized, but the description method in the super class Vehicle is used through super.description, and then some additional information is added, such as the current speed of the car. If you create a new instance of Car and print the output of the description method, you will find that the description information has changed
let car = Car ()
println ("Car: \ (car.description ())")
// Car: 4 wheels; up to 5 passengers; traveling at 0.0 mph
 

2. Rewrite attributes You can rewrite inherited instance attributes or class attributes, provide your own custom getter and setter, or add attribute observers to make the rewritten attributes observe when the attribute value changes. 3. Getters and Setters that rewrite attributes You can provide custom getters (or setters) to rewrite any inherited attributes, regardless of whether the inherited attributes are stored or calculated. The subclass does not know whether the inherited attribute is storage or computational, it only knows that the inherited attribute will have a name and type. When you rewrite an attribute, you must write its name and type. This will enable the compiler to check that the property you rewrite matches the property of the same name and type in the superclass. You can rewrite an inherited read-only attribute as a read-write attribute, as long as you provide getter and setter in the rewritten version of the attribute. However, you cannot rewrite an inherited read-write attribute as a read-only attribute. Note: If you provide a setter in the rewrite attribute, then you must also provide a getter. If you do not want to modify the inherited property value in the getter in the rewritten version, you can directly return super.someProperty to return the inherited value. As shown in the SpeedLimitedCar example below. The following example defines a new class called SpeedLimitedCar, which is a subclass of Car. Class SpeedLimitedCar means a car with a speed limit device installed, and its maximum speed can only reach 40mph. You can achieve this speed limit by overriding the inherited speed attribute
class SpeedLimitedCar: Car {
    override var speed: Double {
    get {
        return super.speed
    }
    set {
        super.speed = min (newValue, 40.0)
    }
    }
}
 

When you set the speed property of a SpeedLimitedCar instance, the implementation of the property setter will check the size of the new value and the limit value of 40mph, and it will set the superclass speed to the smaller of newValue and 40.0. Which of these two values is smaller is determined by the min function, which is a global function in the Swift standard library. The min function receives two or more numbers and returns the smallest of them. If you try to set the speed property of the SpeedLimitedCar instance to a number greater than 40mph, and then print the output of the description function, you will find that the speed is limited to 40mph:
let limitedCar = SpeedLimitedCar ()
limitedCar.speed = 60.0
println ("SpeedLimitedCar: \ (limitedCar.description ())")
// SpeedLimitedCar: 4 wheels; up to 5 passengers; traveling at 40.0 mph
4. Rewrite the property observer (Property Observer) You can add a property observer for an inherited property in property rewriting. In this way, when the value of the inherited property changes, you will be notified, no matter how the property was originally implemented. For more information about the attribute observer, please see the attribute observer. Note: You cannot add attribute observers for inherited constant storage attributes or inherited read-only calculated attributes. The values of these properties cannot be set, so it is not appropriate to provide them with willSet or didSet implementations. Also note that you cannot provide both a rewritten setter and a rewritten attribute observer. If you want to observe changes in the value of an attribute and you have provided a custom setter for that attribute, then you can observe any value changes in the setter. The following example defines a new class called AutomaticCar, which is a subclass of Car. AutomaticCar means automatic car, it can automatically select the appropriate gear according to the current speed. AutomaticCar also provides a customized description method that can output the current gear.
class AutomaticCar: Car {
    var gear = 1
    override var speed: Double {
    didSet {
        gear = Int (speed / 10.0) + 1
    }
    }
    override func description ()-> String {
        return super.description () + "in gear \ (gear)"
    }
}
When you set the Speed property of AutomaticCar, the didSet observer of the property will automatically set the gear property and select a suitable gear for the new speed. Specifically, the attribute observer divides the new speed value by 10, then obtains the nearest integer value downward, and finally adds 1 to get the gear value. For example, when the speed is 10.0, the gear is 1; when the speed is 35.0, the gear is 4:

let automatic = AutomaticCar ()
automatic.speed = 35.0
println ("AutomaticCar: \ (automatic.description ())")
// AutomaticCar: 4 wheels; up to 5 passengers; traveling at 35.0 mph in gear 4
 



Prevent rewriting

You can prevent methods, attributes, or subscripts from being marked as final by overriding them by adding the final feature before declaring keywords. (E.g. final var, final func, final class func, and final subscript) If you rewrite the final method, attribute or subscript, you will get an error at compile time. In extensions, the methods, properties or subscripts you add to the class can also be marked as final in the extension definition. You can mark the entire class as final by adding @final feature (final class) before the keyword class. Such a class cannot be inherited, otherwise it will report a compilation error.
[Study in Swift] Swift Programming Tour --- Inheritance (17)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.