The Switf programming Language 练习代码(3)

//

//  main.swift

//  classTest

//

//  Created by 小强 on 15/12/8.

//  Copyright © 2015 小强. All rights reserved.

//


import Foundation


//  对象和类


class Shape

{

    var numberOfSides = 0;

    let constNumber = 10;

    

    func simpleDescription() -> String

    {

        return "A shape with \(numberOfSides) sides."

    }

    

    func getNumberOfSides(numberOfSides: Int)       //接收参数的方法

    {

        self.numberOfSides = numberOfSides;

    }

};


//  练习 1 使用 let 添加一个常量属性,再添加一个接收一个参数的方法


var shape = Shape();

shape.numberOfSides = 7;

print(shape.simpleDescription());


// 使用 init 来创建一个构造器,deinit 来创建一个析构函数


class NamedShape

{

    var numberOfSides: Int = 0;

    var name: String;

    

    init (name: String)

    {

        self.name = name;

    }

    

    func simpleDescription() -> String

    {

        return "A shape with \(numberOfSides) sides.";

    }

    deinit{}        //  析构函数

};


class Square :NamedShape

{

    var sideLength: Double = 0;

    

    init(sideLength: Double, name: String)

    {

        self.sideLength = sideLength;

        super.init(name: name)

        numberOfSides = 4;

    }

    

    func area() -> Double

    {

        return sideLength * sideLength;

    }

    

  override func simpleDescription() -> String {

        return "A square with sides of length \(sideLength)."

    }

};


let test = Square(sideLength: 5.2, name: "my test square");

print(test.area());

print(test.simpleDescription());


//  练习2 创建 NamedShape 的另一个子类 Circle,构造器接收两个参数,

//  一个是半径一个是名称,实现 area describe 方法


class Circle :NamedShape{

    

    var radius: Double = 0.0;

    

    init(radius: Double, name: String){

        

        self.radius = radius;

        super.init(name: name);

    }

    

    func area() -> Double{

        

        return 3.14 * radius * radius;

    }

    

    override func simpleDescription() -> String {

        return "A circle with radius is: \(radius).";

    }

}


let circle = Circle(radius: 3.0, name: "my test circle");

print(circle.area());

print(circle.simpleDescription());







你可能感兴趣的:(The Switf programming Language 练习代码(3))