chore: add advanced class example
This commit is contained in:
66
examples/advanced/02_polymorphism.peb
Normal file
66
examples/advanced/02_polymorphism.peb
Normal file
@@ -0,0 +1,66 @@
|
||||
class Shape {
|
||||
init(color) {
|
||||
this.color = color
|
||||
}
|
||||
|
||||
name() {
|
||||
return "shape"
|
||||
}
|
||||
|
||||
area() {
|
||||
return 0
|
||||
}
|
||||
|
||||
describe() {
|
||||
print("A", this.color, this.name(), "with area", this.area())
|
||||
}
|
||||
}
|
||||
|
||||
class Rectangle < Shape {
|
||||
init(color, width, height) {
|
||||
super.init(color)
|
||||
this.width = width
|
||||
this.height = height
|
||||
}
|
||||
|
||||
name() {
|
||||
return "rectangle"
|
||||
}
|
||||
|
||||
area() {
|
||||
return this.width * this.height
|
||||
}
|
||||
}
|
||||
|
||||
class Square < Rectangle {
|
||||
init(color, size) {
|
||||
super.init(color, size, size)
|
||||
}
|
||||
|
||||
name() {
|
||||
return "square"
|
||||
}
|
||||
}
|
||||
|
||||
class Circle < Shape {
|
||||
init(color, radius) {
|
||||
super.init(color)
|
||||
this.radius = radius
|
||||
}
|
||||
|
||||
name() {
|
||||
return "circle"
|
||||
}
|
||||
|
||||
area() {
|
||||
return this.radius * this.radius * 3.1415
|
||||
}
|
||||
}
|
||||
|
||||
let rect = Rectangle("red", 3, 4)
|
||||
let square = Square("green", 5)
|
||||
let circle = Circle("blue", 2)
|
||||
|
||||
rect.describe()
|
||||
square.describe()
|
||||
circle.describe()
|
||||
Reference in New Issue
Block a user