SWIFT Chapter11 Inheritance
SWIFT Chapter11 Inheritance
Preventing Overrides
Class Identity
class Shape{ //No inherited from anything
var title="Shape"
func area() ->Double{
return 0.0
}
func description()->String{
return "I am a \(title). My area is \(area())"
}
}
class Square:Shape{
var sideLength = 0.0
override func area() -> Double{
return sideLength*sideLength
}
}
let square=Square()
square.sideLength=4
square.title = "SQUARE"
println(square.area())
println(square.description())
class Circle:Shape{
var radius=0.0
override func area() -> Double{
return M_PI*radius*radius
}
}
class Sphere:Circle{
override func description() -> String{
return super.description()+".My volume is \(volume())"
}
func volume() ->Double{
return (4.0*super.area()*radius)/3.0
}
}
var sphere1 = Sphere()
sphere1.title="Sphere"
sphere1.radius=2.0
var square1 = Square()
square1.title="Square"
square1.sideLength=5.0
// println(sphere.volume())
// println(sphere.description())
func printDescriptionForShape(shape:Shape){
println(shape.description())
}
println(printDescriptionForShape(sphere1))
println(printDescriptionForShape(square1))
Exercise
class Shape{ //No inherited from anything
var title="Shape"
func area() ->Double{
return 0.0
}
func description()->String{
return "I am a \(title). My area is \(area())"
}
}
class Square:Shape{
var sideLength = 0.0
override func area() -> Double{
return sideLength*sideLength
}
}
let square=Square()
square.sideLength=4
square.title = "SQUARE"
println(square.area())
println(square.description())
class Circle:Shape{
var radius=0.0
override func area() -> Double{
return M_PI*radius*radius
}
}
class Sphere:Circle{
override func description() -> String{
return super.description()+".My volume is \(volume())"
}
func volume() ->Double{
return (4.0*super.area()*radius)/3.0
}
}
class Cylinder:Circle{
var height:Double = 0.0