Swift Inheritance and overloading

Source: Internet
Author: User

A class can inherit (inherit) another class's methods (methods), property, and other attributes. When a class inherits from another class, the inheriting class is called the subclass (subclass), and the inherited class is called the superclass (or parent class, superclass). In Swift, inheritance is a basic feature of distinguishing between "class" and other types.

In Swift, classes can invoke and access the superclass's methods, properties, and satellite scripts (subscripts), and can override (override) These methods, properties, and the subordinate script 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).

Define a base class (base classes)

Classes that do not inherit from other classes are 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

}

}

The vehicle class defines the constructor (initializer) to set the value of the property. The constructor is described in detail in the construction process section, where we do a brief introduction to explain how the attributes inherited from the subclass are modified.

The constructor is used to create a new instance of a type. Although constructors are not methods, they are syntactically similar. The work of the constructor is to prepare a new instance for use and to ensure that all properties in the instance have valid initialization values.

The simplest form of a constructor is like an instance method without parameters, using the INIT keyword:

Init () {

Performing the construction process

}

If you want to create a new instance of the vehicle class, use the constructor syntax to invoke the above initializer, which is followed by an empty parenthesis after the class name:

Let somevehicle = Vehicle ()

The constructor for this vehicle class sets some initialization property values (numberofwheels = 0 and maxpassengers = 1) for any vehicle.

The vehicle class defines the common characteristics of a vehicle, but the class itself is not much useful. To make it more practical, you need to refine it further to describe a more specific vehicle.

Subclass Generation (subclassing)

Subclass Generation (subclassing) refers to the creation of a new class on the basis of an existing class. Subclasses inherit the attributes of a superclass and can optimize or change it. You can also add new attributes to subclasses.

To indicate a superclass of a class, write the superclass name after the subclass name, separated by a colon:

Class Someclass:somesuperclass {

Definition of Class

}

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 behind the bicycle class, separated by colons.

We can read this as: "Define a new class called bicycle, which inherits the characteristics of vehicle";

Class Bicycle:vehicle {

Init () {

Super.init ()

Numberofwheels = 2

}

}

Bicycle is a subclass of vehicle, and vehicle is a super class of bicycle. The new bicycle class automatically gets the attributes of the vehicle class, such as the Maxpassengers and Numberofwheels properties. 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 features (bikes only have 2 wheels). The bicycle constructor calls the constructor Super.init () 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, the initializer is not inherited by default, see initializer inheritance and overrides

The default value for Maxpassengers in the vehicle class is already correct for the bike, so it is not changed in the bicycle constructor. The original value of Numberofwheels is incorrect for the bike, so change it to 2 in the initializer.

Bicycle can inherit not only the properties of vehicle, but also its methods. If you create an instance of the bicycle class, you can invoke the description method it inherits from, and you can see that its output property values have changed:

Let bicycle = bicycle ()

println ("Bicycle: (Bicycle.description ())")

Bicycle:2 Wheels; Up to 1 passengers

Subclasses can also continue to be inherited by other classes:

Class Tandem:bicycle {

Init () {

Super.init ()

Maxpassengers = 2

}

}

The example above creates a subclass of bicycle: a two-person bike (tandem). Tandem inherits two attributes from bicycle, and these two properties are inherited by bicycle from vehicle. Tandem does not modify the number of wheels because it is still a bicycle, with 2 wheels. But it needs to modify the value of the maxpassengers because the two-person bike can sit two people.

Note: Subclasses are allowed to modify only the variable properties inherited from the superclass, not the inherited constant properties.

Create an instance of the Tandem class and print its description to see that its properties 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. An instance method of a class is inherited by all subclasses of the class.

Rewrite (overriding)

Subclasses can be inherited from instance methods (instance method), class methods, instance properties (instance property), or a subordinate script (subscript) that provides its own custom implementation (implementation). We call this behavior rewriting (overriding).

If you want to override an attribute, you need to precede the override definition with the Override keyword. By doing so, you have shown that you are trying to provide a rewrite version, rather than providing the same definition in the wrong way. Unexpected overrides can cause unpredictable errors, and any overrides that lack the override keyword are diagnosed as errors at compile time.

The override keyword reminds the Swift compiler to check if the class's superclass (or one of its parent classes) has a claim that matches the rewritten version. This check will ensure that your rewrite definition is correct.

Accessing superclass methods, properties, and subordinate scripts

When you override a superclass's method, property, or satellite script in a subclass, it is sometimes useful to use an already existing superclass implementation in your rewritten version. For example, you can optimize the behavior of an existing implementation, or store a modified value in an inherited variable.

In the right place, you can access the superclass version of a method, property, or satellite script by using the Super prefix:

In the overridden implementation of method SomeMethod, the SomeMethod method of the superclass version can be called Through Super.somemethod ().

In the overridden implementation of the getter or setter of the property Someproperty, the Someproperty property of the superclass version can be accessed through Super.someproperty.

In the overridden implementation of a subordinate script, you can access the same satellite script in the superclass version through Super[someindex].

overriding method

In subclasses, you can override an inherited instance method or a class method, providing a custom or alternative method implementation.

The following example defines a new subclass of vehicle, called Car, which overrides 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 property speed, which is of type double and the default value is 0.0, which means "0 mph". Car has its own initializer, which sets the maximum number of passengers to 5, and the number of wheels is set to 4.

Car Overrides the inherited description method, whose declaration is consistent with the description method in vehicle, with the override keyword prepended to the declaration.

The description method in car is not completely customizable, but instead uses the description method in the superclass vehicle through Super.description, and then appends some additional information, 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

overriding properties

You can override an inherited instance property or Class property, provide your own custom getter and setter, or add a property observer to make the overridden property observe when the property value changes.

Overriding properties of getters and setters

You can provide a custom getter (or setter) to override any inherited attribute, regardless of whether the inherited attribute is a stored or computed property. Subclasses do not know whether inherited attributes are stored or computed, and only know that inherited attributes have a name and type. When you rewrite a property, it is necessary to write its name and type. This allows the compiler to check that the property you are overriding matches a property of the same type in the superclass.

You can rewrite an inherited read-only property as a read-write property, and you only need to provide getter and setter in the overridden version of the property. However, you cannot override an inherited read-write property to a read-only property.

Note: If you provide a setter in the Override property, then you must also provide a getter. If you do not want to modify inherited property values in a getter in the rewritten version, you can return Super.someproperty directly 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. The class Speedlimitedcar represents a car with a speed limiting device, which can reach speeds of up to 40mph. You can implement this speed limit by overriding the slow property of the inheritance:

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 checks the size of the new value and the limit value 40mph, which sets the speed of the superclass 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, returning 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 velocity 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

overriding property observers (properties Observer)

You can add property observers to an inherited property in property overrides. In this way, when the inherited property value changes, you are notified, regardless of how the property was originally implemented. For more information about the property watcher, see Property Watcher.

Note: You cannot add a property observer for inherited const-stored properties or inherited read-only computed properties. The values of these properties cannot be set, so it is inappropriate to provide them with willset or Didset implementations. Also note that you can not provide both the overridden setter and the overridden property watcher. If you want to observe the change in the property value, and you have provided a custom setter for that property, you can observe any value change in the setter.

The following example defines a new class called Automaticcar, which is a subclass of car. Automaticcar means auto-stop, which automatically selects the right gear according to the current speed. The Automaticcar also provides a custom description method to output the current stop.

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"

}

}

When you set the Speed property of the Automaticcar, the Didset Viewer of the property automatically sets the Gear property to select a suitable stop for the new velocity. Specifically, the property observer divides the new speed value by 10, then the nearest integer value down, and finally the value of the gear gear. For example, when the speed is 10.0, the stop is 1 and the speed is 35.0, the stop 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 them from being rewritten by marking methods, properties, or subordinate scripts as final, just by adding the @final attribute to the Declaration keyword. (Example: @final var, @final func, @final class func, and @final subscript)

If you rewrite the final method, the property, or the subordinate script, you will get an error at compile time. In the extension, the method that you add to the class, a property, or a subordinate script can also be marked as final in the extension's definition.

You can mark an entire class as final by adding the @final attribute (@final Class) before the keyword class, so that the class is not inherited, or a compilation error is reported.

Swift Inheritance and overloading

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.