Swift Programming Language-how to use Inheritance in Swift, swiftlanguage

Source: Internet
Author: User

Swift Programming Language-how to use Inheritance in Swift, swiftlanguage

One class can inherit the methods, properties, and other features of the other class. When a class inherits other classes, the inherited class is called subclass, And the inherited class is called superclass (or parent class, superclass ). In Swift, inheritance is a basic feature that distinguishes a class from other types.

 

In Swift, classes can call and access superclasses, attributes, and subscripts, and override these methods, the behavior of attributes and affiliated scripts to optimize or modify them. Swift checks whether your override definition has a matching definition in the superclass to ensure that your rewrite behavior is correct.

 

You can add a property observer (property observer) to the property inherited from the class. When the property value changes, the class will be notified. You can add an attribute observer for any attribute, whether it is originally defined as a stored property or a compute property ).

 

 

Define a Base class)

Classes that do not inherit from other classes are called base calss ).

 

Note:

 

Classes in Swift are not inherited from a general base class. If you do not specify a superclass for your defined class, the class will automatically become the base class.

The following example defines a base class named Vehicle. This base class declares two attributes that are common to all vehicles (numberOfWheels and maxPassengers ). These attributes are used in the description method. This method returns a String-type description of vehicle features:

 

class Vehicle {   var numberOfWheels: Int   var maxPassengers: Int   func description() -> String {       return "\(numberOfWheels) wheels; up to \(maxPassengers)passengers"    }   init() {       numberOfWheels = 0       maxPassengers = 1    }}


The Vehicle class defines the constructor (initializer) to set the attribute value. The constructor will introduce the constructor in detail in the constructor section. Here we will give a brief introduction to explain how the inherited attributes in sub-classes are modified.

 

The constructor is used to create a new instance of a certain type. Although the constructor is not a method, the two are similar in syntax. The constructor prepares a new instance for use and ensures that all attributes of the Instance have valid initialization values.

 

The simplest form of the constructor is like an instance method without parameters. Use the init Keyword:

 

Init () {// execute the construction process}


If you want to create a new instance of the Vehicle class, use the constructor syntax to call the initialization tool above, that is, the class name is followed by an empty parentheses:

 

let someVehicle = Vehicle()


The Vehicle class constructor sets initialization attribute values for any Vehicle (numberOfWheels = 0 and maxPassengers = 1 ).

 

The Vehicle class defines the common characteristics of vehicles, but it is not very useful. To make it more practical, You need to further refine it to describe more specific vehicles.

 

 

Subclassing)

Subclassing refers to creating a new class based on an existing class. Subclass inherits the features of a superclass and can be optimized or changed. You can also add new features for the subclass.

 

To specify the superclass of a class, write the superclass name behind the subclass name and separate it with a colon:

 

Class SomeClass: SomeSuperclass {// class definition}


In the next example, we will define a more specific vehicle class called Bicycle. This new class is created based on the Vehicle class. Therefore, you need to put the Vehicle class behind the Bicycle class and separate them with colons.

 

We can read this:

 

"Define a new class called Bicycle, which inherits the features of Vehicle ";

 

class Bicycle: Vehicle {   init() {       super.init()       numberOfWheels = 2    }}


A Bicycle is a subclass of Vehicle, and a Vehicle is a superclass of a 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 the subclass or add new features to better describe the Bicycle class.

 

The Bicycle class defines a constructor to set its custom features (the Bicycle has only two wheels ). The Bicycle constructor calls the constructor super. init () of its parent Vehicle class to ensure that the Vehicle class has initialized them before the Bicycle class tries to modify the inherited attributes.

 

Note:

 

Unlike Objective-C, in Swift, the initiators do not inherit by default. For details, see the inheritance and rewriting of the initiaters.

The default value of maxPassengers in the Vehicle class is correct for bicycles, so it is not changed in the Bicycle constructor. The original numberOfWheels value is incorrect for the bicycle, so it is changed to 2 in the initialization tool.

 

A Bicycle can inherit not only the attributes of Vehicle, but also its methods. If you create a Bicycle class instance, you can call the description method inherited by it, and you can see that the output property value has changed:

 

let bicycle = Bicycle()println("Bicycle:\(bicycle.description())")// Bicycle: 2 wheels; up to 1 passengers


Subclass can be inherited by other classes:

 

class Tandem: Bicycle {   init() {       super.init()       maxPassengers = 2    }}


In the preceding example, a subclass of Bicycle is created: Double Bicycle (tandem ). Tandem inherits two attributes from Bicycle, which are inherited from Vehicle. Tandem does not modify the number of wheels because it is still a bicycle with two wheels. But it needs to modify the value of maxPassengers, because a two-person bicycle can take two people.

 

Note:

 

Subclass only allows you to modify attributes of variables inherited from a superclass, but not attributes of constants inherited from them.

Create an instance of the Tandem class and print its description to see that its attributes have been updated:

 

let tandem = Tandem()println("Tandem:\(tandem.description())")// Tandem: 2 wheels; up to 2 passengers


Note that the Tandem class also inherits the description method. The instance method of a class is inherited by all subclasses of the class.

 

 

Overriding)

Subclasses can be inherited instance methods, class methods, instance properties, or subscripts) provides customized implementation (implementation ). We call this behavior overriding ).

 

If you want to rewrite a feature, you need to add the override keyword before the rewrite definition. By doing so, you indicate that you want to provide an rewrite version, rather than mistakenly providing the same definition. Unexpected rewriting may lead to unpredictable errors. Any rewriting without the override keyword will be diagnosed as an error during compilation.

 

The override keyword reminds the Swift compiler to check whether the superclass (or one of its parent classes) of the class matches the declaration of the override version. This check ensures that your rewrite definition is correct.

 

Methods, attributes, and scripts for accessing the superclass

When you override a superclass method, attribute, or ancillary script in a subclass, it is helpful to use an existing superclass implementation in your override version. For example, you can optimize existing implementations or store a modified value in an inherited variable.

 

In a proper place, you can use the super prefix to access methods, attributes, or ancillary scripts of the superclass version:

 

In the method someMethod rewriting implementation, super. someMethod () can be used to call the someMethod method of the superclass version.

In the rewriting implementation of the getter or setter attribute of someProperty, super. someProperty can be used to access the someProperty attribute of the super-class version.

In the rewrite Implementation of the ancillary script, you can use super [someIndex] to access the same ancillary script in the superclass.

Rewrite Method

In subclass, You can override the inherited instance methods or class methods to provide a customized or alternative method implementation.

 

The following example defines a new subclass of Vehicle called Car, which overwrites the description method inherited from the Vehicle class:

 

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-type attribute speed, which belongs to the Double type. The default value is 0.0, indicating that "the speed is 0 miles per hour ". The Car has its own initialization device. It sets the maximum number of passengers to 5 and the number of wheels to 4.

 

Car overwrites the inherited description method. Its declaration is consistent with the description method in Vehicle. The override keyword is added before the declaration.

 

The description method in Car is not completely customized. Instead, it uses the description method in the super class Vehicle through super. description, and then append some additional information, such as the current speed of the Car.

 

If you create a new Car instance and print the description method output, 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


Rewrite attributes

You can override inherited instance attributes or class attributes, provide custom getter and setter, or add an attribute observer to observe when the attribute value is changed.

 

Getters and Setters of the override attribute

 

You can provide custom getter (or setter) to override any inherited attributes, whether they are stored or computed. The subclass does not know whether the inherited attributes are stored or computed. It only knows that the inherited attributes have a name and type. When you override an attribute, you must write its name and type. In this way, the compiler can check that the attributes you overwrite match those of the same name in the super class.

 

You can rewrite an inherited read-only attribute to a read/write attribute. You only need to provide the getter and setter attributes in the rewrite attribute. However, you cannot rewrite an inherited read/write attribute to a read-only attribute.

 

Note:

 

If you provide setter in the rewrite attribute, you must also provide getter. If you do not want to modify the inherited property value in the getter of the rewrite version, you can directly return super. someProperty to return the inherited value. As shown in the following example of SpeedLimitedCar.

The following example defines a new class called SpeedLimitedCar, which is a child class of Car. SpeedLimitedCar indicates a vehicle with a speed limiting device installed. Its maximum speed can only reach 40 mph. You can overwrite the inherited speed attribute to achieve this speed limit:

 

class SpeedLimitedCar: Car {   override var speed: Double  {   get {       return super.speed    }   set {       super.speed = min(newValue, 40.0)    }    }}


When you set the speed attribute of a SpeedLimitedCar instance, the implementation of the property setter checks the size of the new value and the limit value of 40mph, it sets the speed of the superclass to the smaller value in newValue and 40.0. Which of the two values is smaller depends on 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 attribute of the SpeedLimitedCar instance to a value greater than 40 mph and print the output of the description function, you will find that the speed is limited to 40 mph:

 

let limitedCar = SpeedLimitedCar()limitedCar.speed = 60.0println("SpeedLimitedCar:\(limitedCar.description())")// SpeedLimitedCar: 4 wheels; up to 5passengers; traveling at 40.0 mph


Property Observer)

 

You can add an attribute observer for an inherited attribute in the attribute rewriting. In this way, when the inherited attribute value changes, you will be notified, no matter how the property was originally implemented. For more information about the attribute observer, see attribute observer.

 

Note:

 

You cannot add an attribute observer to the inherited attributes of constant storage or read-only computing. The values of these attributes cannot be set. Therefore, it is inappropriate to provide willSet or didSet implementations for them. In addition, you cannot provide the rewritten setter and the rewritten attribute Observer at the same time. If you want to observe the changes in the property value and you have provided custom setter for that property, you can observe any changes in the setter.

The following example defines a new class named AutomaticCar, which is a child class of Car. AutomaticCar indicates an automatic car. It can automatically select an appropriate gear block based on the current speed. AutomaticCar also provides a custom description method to 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 attribute of AutomaticCar, The didSet observer of the attribute will automatically set the gear attribute to select a proper gear for the new speed. Specifically, the attribute observer divides the new speed value by 10, obtains the nearest integer downward, and Adds 1 to get the gear value of the gear. For example, when the speed is 10.0, the block is 1; when the speed is 35.0, the block is 4:

 

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


 

Prevent Rewriting

You can mark methods, attributes, or ancillary scripts as final to prevent them from being overwritten. You only need to add the @ final Attribute before declaring the keywords. (For example, @ final var, @ final func, @ final class func, and @ finalsubscript)

 

If you overwrite the final method, attribute, or ancillary script, an error will be reported during compilation. In the extension, the method, attribute, or ancillary script you add to the class can also be marked as final in the extension definition.

 

You can add the @ final feature (@ final class) before the keyword class to mark the entire class as final. Such classes cannot be inherited; otherwise, a compilation error is reported.


In java, when is interface used?

I don't think everyone can say this well. In my own experience, I would like to sum up a more abstract sentence:
To perform a multi-state operation, use the interface
If you have special requirements, use inheritance. In this case, you can rewrite methods, extend methods, and so on.
Many of the above two are overlapping and are not isolated.

In java, the Object Class; Inheritance; what is the name of an Object in Chinese?

Object Class
Inheritance is interface

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.