Swift Learning-14--Inheritance

Source: Internet
Author: User
Tags instance method

A class can inherit another class's methods, properties, and other characteristics, when a class inherits from another class, the inheriting class is called a subclass, the inherited class is called the parent class, or (superclass), in Swift, inheritance is a basic feature that distinguishes [class] and other types

In Swift, classes can invoke and access superclass methods, properties, and subscripts, and can override these methods, attributes, and subscripts to refine or modify their behavior

Swift checks to see if your rewrite definition has a matching definition in the superclass, one time to ensure that your rewrite behavior is correct

You can add a property observer to a property that inherits from a class, so that when the value of the property changes, the class is notified that a property observer can be added for any attribute, whether he is originally defined as a storage attribute or a computed property

Define a base class

A class that does not inherit from another class, called a base class

Note: Classes in Swift do not inherit from a common base class, which automatically becomes the base class if you do not specify a superclass for the class you define.

An example defines a base class called Vehicle, which declares a storage property named Currentspeed with a default value of 0.0 (attribute type is inferred as Double), and the value of the Currentspeed property is read-only by a String type The description attribute is used to create a description of the vehicle. The Vehicle base class also defines a method called Makenoise, which actually Vehicle the instance to do anything, but is then customized by the Vehicle subclass.

Class vehicle{

var currentspeed = 0.0

var description:string {

Return "Traveling at \ (currentspeed) miles per hour"

}

Func makenoise () {

Not doing anything.

}

}

Let somevehicle = Vehicle ()

Print ("Vehicle: \ (somevehicle.description)")

Sub-class generation

Subclass generation refers to the creation of a new class on the basis of an existing class, which inherits the attributes of the superclass and can be further refined, and you can also add new attributes to subclasses

In order to indicate the superclass of a class, the superclass name is unloaded after the subclass name, separated by a colon:

Class bicycle:vehicle{

var Hasbasket = False

}

The new Bicycle class automatically obtains all the properties and methods of the Vehicle class, in addition to the attributes he inherits, the Bicycle class also defines a storage property with a default value of False Hasbasket (Bool type)

By default, any new Bicycle instances that you create will not have a basket, but you can set the Hasbasket property for a specific Bicycle instance to ture

Let bicycle = bicycle ()

Bicycle.hasbasket = True

You can also modify the Currentspeed property inherited by the Bicycle instance, and the Descriotion property that the query instance inherits:

Bicycle.currentspeed = 15.0

Print ("Bicycle: \ (bicycle.currentspeed)")

Subclasses can also continue to be inherited by other classes The following example creates a subclass named tandem (two-person bike) for bicycle:

Class Tandem:bicycle {

var currentnumberofpassengers = 0

}

Tandem inherits all the properties and methods from bicycle, which in turn inherits all the properties and methods of vehicle. Tandem also added a new storage-type attribute called Currentnumberofpassengers, with a default value of 0.

If you create an instance of tandem, you can use all of its new properties and inherited properties, and you can query the read-only attribute description inherited from vehicle:

Let tandem = Tandem ()

Tandem.hasbasket = True

Tandem.currentnumberofpassengers = 2

Tandem.currentspeed = 22.0

Print ("Tandem: \ (tandem.description)")

Printed: "Tandem:traveling at 22.0 miles per hour"

Rewrite

Subclasses can provide their own custom implementations for inherited instance methods, class methods, instance properties, or subscripts, and we call this behavior rewriting

If you want to override an attribute, you need to precede the override definition with the Override keyword, so that you indicate that you want to provide a rewrite version, rather than mistakenly provide an identical definition, unexpected overrides can cause unpredictable errors, any overrides that are missing the override keyword will be diagnosed as error at compile time

The override keyword reminds the Swift editor to check the superclass of the class and if there is a claim matching the rewritten version, this check will ensure that your rewrite definition is correct

Accessing superclass methods, properties, and subscripts

When you override a superclass's method, property, or subscript in a subclass, it can sometimes be useful to use an already existing superclass implementation in your rewritten version, for example, you can completely refine an already implemented behavior, or store a modified value in an inherited variable

In the right place, you can access the superclass version of the method by using the super prefix, attribute or subscript

1: In the overridden implementation of Method SomeMethod (), the superclass version of the SomeMethod () method can be called through Super.somemethod ().

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

3: In the overriding implementation of the subscript, you can access the same subscript in the superclass version through Super[someindex].

overriding method

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

Class train:vehicle{

Override Func Makenoise () {

Print ("Choo Choo")

}

}

This example defines a new subclass of Vehicle, called Train, which overrides the Makenoise () method inherited from the Vehicle class

Let train = Train ()

Train.makenoise ()

overriding properties

You can override inherited instance properties or type properties, provide your own custom getter and setter, or add property observers so that overridden properties can also be observed when the value changes

Override properties for Getter and setter

You can provide custom getter and setter to rewrite any inherited attributes, regardless of whether inherited attributes are stored or computed, subclasses do not know if inherited attributes are stored or computed, and only know that inherited attributes have a name and type, and you are rewriting a property, you must write out its name and type so that the compiler can check if 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, just provide the getter and setter in the overridden version of the property, but you cannot rewrite an inherited read-write property as a read-only property

Note: If you provide a setter in the override attribute, then you must also provide getter, if you do not want to modify the inherited property value in the getter in the rewritten version, you can return the inherited value directly through Super.someproperty, where som Eproperty is the name of the property you want to override

Class car:vehicle{

var gear = 1

Override Var description:string{

return super.description + "in gear" (gear)

}

}

This example defines a new class called Car, which is a subclass of vehicle. This class introduces a new storage-type property called Gear, which defaults to an integer of 1. The car class overrides the Description property, which inherits from vehicle, and provides a custom description that contains the current file position:

The overridden Description property first calls Super.description to return the Description property of the Vehicle class, and the Car class version of description adds custom content at the end

Let car = car ()

Car.currentspeed = 25.0

Car.gear = 3

Print ("Car: \ (car.description)")

overriding property observers

You can add a property observer to an inherited property by overriding the property, so that when the inherited property value changes, you are notified that no matter which property was originally implemented

Note: You cannot add property observers for inherited constants that store properties or inherited read-only computed properties, and the values of these properties cannot be set. So it is inappropriate to provide them with Willset and Didset.

In addition, 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, then you can observe any value change in the setter.

Class automaticcar:car{

Override Var currentspeed:double{

didset{

Gear = Int (currentspeed/10.0) + 1

}

}

}

When you set the Currentsprrd property of the Automaticcar, the Didset observer for the property automatically sets the Gear property, selecting a suitable gear for the new speed, in particular, the property observer divides the new speed value by 10, and then the nearest whole The value of the gear gear, which is finally added

Let automatic = Automaticcar ()

Automatic.currentspeed = 35.0

Print ("Automaticcar: \ (automatic.description)")

Prevent rewriting

You can prevent them from being rewritten by marking methods, attributes, or subscripts as final, just by adding the final modifier to the Declaration keyword

such as: Final Var, final func, Final class func, final subscript

If you rewrite the method with the final tag, the attribute or subscript, at compile time or error,

A method, property, or subscript in a class extension can also be marked as fnial in the definition of an extension

You can mark an entire class as final by adding the final modifier (final Class) before the keyword class, such that a class cannot be inherited, and attempting to inherit such a class can result in a compilation error

Swift Learning-14--Inheritance

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.