11. 子类,格式:类名:父类名{}
class square: nameShape
{
var sidelength:Double
init(name:String , sidelength:Double)
{
self.sidelength = sidelength
super.init(name: name)
numberofside = 4
}
func area() -> Double
{
return sidelength * sidelength
}
override func simpledescription() -> String {
return "a square with sides of legth \(sidelength)"
}
}
let testSquare = square(name:"my text square" , sidelength: 5.2)
testSquare.area()
testSquare.simpledescription()
当想覆盖父类的方法时,需要使用override,不然会出现报错;
想初始化父类的值时,如果父类使用init来初始化,那需要调用super.init()来进行重新赋值
创建实例的时候也可以判断传递进来的值是否符合要求,要是不符合要求就会传递一个nil,初始化函数需要用init?(){}
class Circle: nameShape
{
var radius:Double
init?(radius:Double , name:String)
{
self.radius = radius
super.init(name: name)
numberofside = 20
if radius < 0
{
return nil
}
}
override func simpledescription() -> String {
return "a circle with a radius of \(radius)"
}
}
var circle = Circle(radius: 3.0 , name: "no name")
var failCircle = Circle(radius: -7.0 , name: "stenf")
circle?.simpledescription()
failCircle?.simpledescription()
circle?.name
failCircle?.name
|
请发表评论