多态在不同语言的展示:
摘要:
分别展示在Go 和Java中是实现的不同
package main
import "fmt"
func main() {
t := &Triangle{6, 8}
s := &Square{8}
shapes := []Shape{t, s}
for n, _ := range shapes {
fmt.Println("1", shapes[n])
fmt.Println("2", shapes[n].Area())
}
}
type Shape interface {
Area() float64
}
type Square struct {
sidelen float64
}
type Triangle struct {
Bottom float64
Height float64
}
func (t *Triangle) Area() float64 {
return (t.Bottom * t.Height) / 2
}
func (sq *Square) Area() float64 {
return sq.sidelen * sq.sidelen
}
Java
class Shape {
void draw() {}
}
class Circle extends Shape {
void draw() {
System.out.println("Circle.draw()");
}
}
class Square extends Shape {
void draw() {
System.out.println("Square.draw()");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("Triangle.draw()");
}
}
参考: