doushan15559 2014-06-15 18:01
浏览 58
已采纳

Google Go中等效的抽象类/方法(Java)

I am new to Go and I'm wondering how I can implement a structure similar to abstract classes & methods in Java. In Java, I'd do the following:

abstract class A{

 static method1(){
  ...
  method2();
  ...
 }

 abstract method2();

}

class B extends A{

 method2(){
  ...
 }

}

class C extends A{

 method2(){
  ...
 }

}

I know about interfaces and structs. I could build an interface and then a struct to implement method1. But what about method2? I know that I can embed one interface in another and also a struct as a field of another struct. But I don't see a way to implement my structure with those methods.

The only solution I see is to implement method1 both in class B and class C. Isn't there another way?

Note: of course in my case it's not just one method. Also I've got a hierarchy of abstract classes and don't really want to move everything down to the 'subclasses'.

The examples I've found on the internet are mostly with only one method per interface. It would be great if one of you guys could give me a hint here! Thanks.

  • 写回答

5条回答 默认 最新

  • douxieshang5577 2014-06-15 23:21
    关注

    Since Go does not have static methods in the OOP sense, you often see those types of methods being implemented as package level functions:

    package mypackage
    
    func() Method1() { ... } // Below I will call it Function instead
    

    Such package level functions would then take an interface as an argument. Your code would in that case look something like this:

    package main
    
    import "fmt"
    
    type Methoder interface {
        Method()
    }
    
    func Function(m Methoder) {
        m.Method()
    }
    
    type StructB struct{}
    
    func (s *StructB) Method() { fmt.Println("StructB") }
    
    type StructC struct{} // You can do some "inheritance" by embedding a base struct
    
    func (s *StructC) Method() { fmt.Println("StructC") }
    
    func main() {    
        b := &StructB{}
        Function(b)    
    }
    

    Output:

    StructB
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路