接口
Java接口
public interface Shape {
String getName();
void printShape();
}
public class Point implements Shape {
public int x;
public int y;
@Override
public String getName() {
return "Point";
}
@Override
public void printShape() {
System.out.println("I`m a Point");
}
}
Golang
import (
"fmt"
)
type Shape interface {
GetName() string
PrintShape()
}
type Point struct {
x int32
y int32
}
func (point *Point) GetName() string {
return "Point"
}
func (point *Point) PrintShape() {
fmt.Printf("I`m a Point")
}
func main() {
var point Shape = &Point{x: 10, y: 100}
switch point.(type) {
case Shape:
fmt.Printf("Type is Shape\n")
default:
fmt.Printf("unknown type\n")
}
fmt.Printf("GetName:%s\n", point.GetName())
point.PrintShape()
}
标准输出:
Type is Shape
GetName:Point
I`m a Point
继承
Java继承
public class Circle extends Point{
private int radius;
public int GetRadius() {
return radius;
}
}
Golang继承
import (
"fmt"
)
type Shape interface {
GetName() string
PrintShape()
}
type Point struct {
x int32
y int32
name string
}
func (point *Point) GetName() string {
return point.name
}
func (point *Point) PrintShape() {
fmt.Printf("I`m a %s\n", point.name)
}
type Circle struct {
Point // 在Circle中直接将Point作为一个field,就实现了继承。Golang中实现继承,采用“组合”的思想
radius int32
}
func (circle *Circle) GetRadius() int32 {
return circle.radius
}
func main() {
circle := &Circle{}
circle.x = 10
circle.y = 100
circle.name = "Circle"
circle.radius = 50
fmt.Printf("GetName:%s\n", circle.GetName())
circle.PrintShape()
fmt.Printf("x:%d, y:%d, radius:%d\n", circle.x, circle.y, circle.radius)
}
标准输出
GetName:Circle
I`m a Circle
x:10, y:100, radius:50