Swift: Object-oriented (inheritance and construction methods)

Source: Internet
Author: User

First, inheritance

1. The class defined in swift, if not inherited from any class, is the base class. This is not the same as the class defined in Objective-c, and the default base class for classes defined in Objective-c is nsobject.
2. Overriding the methods and properties of the parent class, you must use the Override keyword (which is clearer, and it is easy to see whether it is the parent class method or the method in your own class).
3. If the class, method, or property is preceded by a final modification, it is not allowed to be inherited or overridden.

Class Inheritance Relationship Demo:

Class Animal {        var speed:int = 1        func run () {        println ("Animal is Running")    }}class dog:animal {        ove Rride var speed:int {        get {            return super.speed        }        set {            if newvalue > {                super.speed = 100            } else {                super.speed = newvalue            }        }    }        override Func run () {        println ("Dog is running ")    }}

second, the construction method

In Swift, the storage properties have to be initialized at the time of definition, as I mentioned in swift: Object-oriented (attributes). If we do not initialize, we can also complete the initialization work in the construction method.

Features of the construction method in Swift:

1. The method is named Init.

2. No func keyword.

3. No return value.

Demo:

Class Person {    var name:string    var age:int        init (name:string, age:int) {        self.name = name        self.age = Age    }}var p = person (name: "Rose", age:30)

in this case, there are two storage properties, name and age, which are not initialized at the time of definition, but we can do their initialization in the constructor of Init (Name:string, Age:int). Self.name and Self.age are the two attributes defined, and name and age are the values of variables passed by the outside world.

Iii. specifying the construction method (designated) and the convenient construction method (Convenience)

There are many rules regarding the use of the specified construction method and the convenient construction method.

1. Only a convenient construction method can invoke other constructor methods of the current class.

Class Person {    var name:string    var age:int        init (name:string, age:int) {        self.name = name        self.age = Age    }        init (name:string) {        self.init (name:name, Age:10)    }}

In the previous example, an attempt was made to call the constructor of Init (Name:string, Age:int) in the constructor of Init (name:string), and the default value for age is 10. But the program will directly error.


As you can see, the error message is obvious, prompting you to add convenience before the init (name:string) Construction method to make this construction method a convenient construction method.

2. Constructor method to invoke parent class only if constructor method is specified

Class Person {    var name:string    var age:int        init (name:string, age:int) {        self.name = name        self.age = Age    }        convenience init (name:string) {        self.init (name:name, age:10)    }}class Jack:person {    Convenience init (name:string) {        super.init (name:name, age:20)    }}

In the example above, an attempt was made to invoke the specified constructor method init (name:string, Age:int) of the parent class person in the convenience init (name:string) of Jack, the subclass. But the program will error.


So, we're going to remove the convenience keyword from Jack's class. Make the direct constructor method of the subclass call the direct construction method of the parent class.

3. The specified construction method with a parameter overrides the invocation of the default parameterless specified constructor method.

In a class defined in Swift, there is a default parameterless constructor that is not displayed. For example:

Class Person {}

it actually has a init () {} specifying the constructor method, which is why you can write the following code to accomplish the initialization of the object.

var p = person ()

However, if you write a constructor that has a parameter specified in the code, the default parameterless constructor is overwritten. For example:

Class Person {    var name:string    var age:int    init (name:string, age:int) {        self.name = name        self.age = Age    }}

at this point you can call
var p = person ()
This code will directly error.


However, if you want to either call the parameterless constructor or have a constructor method. Then you can write the default method as long as you want.

Class Person {    var name:string    var age:int        init () {        self.name = "Rose"        self.age = +    }        init (Name:string, Age:int) {        Self.name = name        Self.age = Age    }}

At this point you can call the following code, which is perfectly possible.

var p = person () var p2 = person (name: "Tick", age:20)
4. If there is a specified constructor method with a parameter in the parent class, the specified construction method of the child class does not automatically invoke the parent class with the specified constructor method without a parameter .

Class Person {    var name:string    var age:int        init (name:string, age:int) {        self.name = name        self.age = Age    }}class Jack:person {    override init (name:string, age:int) {        super.init ()    }}

The subclass Jack's Construction method calls the parent class's init default parameterless constructor, and will directly error.


So we can directly call the parent class in the constructor of the subclass of the constructor method can be, the code is as follows:

Super.init (Name:name, Age:age)

5. A constant property can only be initialized in the constructor method of the class in which it is defined and cannot be initialized in a subclass.

Class Person {    var name:string    var age:int let    gender:string        init (name:string, Age:int, Gender:strin g) {        self.name = name        Self.age = Age        Self.gender = Gender    }}class Jack:person {    override init (name:s Tring, Age:int, gender:string) {        self.age = ten        Self.gender = "W"        super.init (Name:name, age:age, Gender: gender)    }}

Notice that the gender defined in person is a constant, so I tried to initialize it in a subclass and it failed. Error message.



The knowledge about the construction method seems to be a bit complicated to open up, we can also analyze the following two station flowchart to analyze the above mentioned knowledge points.




Four, the Destruction method

The destructor method in Swift is similar to the processing of dealloc in Objective-c.

Demo:

Class Dog {    deinit {        println ("Dog Die")    }}func Onedog () {    var d = Dog ()}println ("New Dog") Onedog () println ("Game over")

After the Onedog function is executed, the D variable is destroyed, the dog object loses a strong reference and is destroyed, and the destructor method is called Deinit

Final print Results
"New Dog"
"Dog die"
"Game over"

Note: Before an object is freed, it automatically calls its own destructor, and then calls the destructor of the parent class one layer at a level.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift: Object-oriented (inheritance and construction methods)

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.