Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalence of abstract classes/methods (Java) in Google Go

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.

like image 638
User42 Avatar asked Jun 15 '14 18:06

User42


People also ask

Can you call methods from an abstract class?

You can call only static methods of an abstract class (since an instance is not required).

Can a Java class have abstract methods?

Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also.

Can an abstract class define both abstract methods and non-abstract methods?

Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods. For an abstract class, we are not able to create an object directly.

Do we need to implement all the methods of abstract class in Java?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.


1 Answers

You can have composite interfaces, for example from the io package :

http://golang.org/src/pkg/io/io.go?s=2987:3047#L57

type Reader interface {
    Read(p []byte) (n int, err error)
}
type Writer interface {
    Write(p []byte) (n int, err error)
}

type ReadWriter interface {
    Reader
    Writer
}

As a side note, don't try to implement java code using go, try to learn the Go Way.

like image 184
OneOfOne Avatar answered Oct 19 '22 03:10

OneOfOne