Sobes.tech
Junior

What are the similarities and differences between a regular class and an abstract class?

sobes.tech AI

Answer from AI

In Golang, there is no concept of "regular class" and "abstract class" in the way they exist in object-oriented languages like Java or C#.

However, their functionality can be simulated using structures and interfaces.

Similarity (using structures and interfaces in Golang):

  • State (data): A structure can contain fields, just like a regular class stores properties.
  • Behavior (methods): Methods can be attached to a structure, which define its behavior, similar to methods of a regular class.
  • Common contract (for abstract class and interface): An interface in Golang defines a set of methods that any structure "implementing" this interface must provide. This is similar to how an abstract class or interface in other languages sets a contract for inheriting or implementing classes.

Difference (in the context of Golang):

Attribute "Regular class" (structure with methods) "Abstract class" (interface + structures)
Direct creation You can create an instance of a structure. You cannot create an instance of an interface.
Method implementation All methods attached to the structure have implementations. An interface only declares methods, but does not implement them.
Inheritance No explicit inheritance in the traditional sense. Composition (embedding structures) can be used. Interfaces are not inherited but implemented by structures.
Implementation obligation No obligation to implement a specific set of methods, except those attached to the structure. Any structure that "implements" a Golang interface must provide implementations for all its methods.
State storage (fields) The structure can contain data fields. Interfaces do not contain data fields.

Example of simulation:

// interface simulating an abstract class
 type Shape interface {
	Area() float64
	Perimeter() float64
}

// structure simulating a regular class
 type Circle struct {
	Radius float64
}

// implementation of interface methods for Circle
func (c Circle) Area() float64 {
	return 3.14 * c.Radius * c.Radius
}

func (c Circle) Perimeter() float64 {
	return 2 * 3.14 * c.Radius
}

// Another structure implementing the interface
type Rectangle struct {
	Width, Height float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
	return 2 * (r.Width + r.Height)
}

In this example, Shape acts as a contract (similar to an abstract class or interface in other languages), and Circle and Rectangle are concrete implementations (analogous to regular classes). We can create instances of Circle and Rectangle, but cannot instantiate Shape directly. Both structures are required to implement the Area() and Perimeter() methods to "implement" the Shape interface.