Abstract classes

Demonstrates abstract classes and methods; Go uses interfaces plus composition, Rust uses traits, JS relies on conventions.

C C23

C23
#include <stdio.h>

// "abstract class" idiom: only the vtable interface is exposed; no valid Shape can be constructed without a vtable
typedef struct {
    double (*area)(const void *self); // abstract method: subtypes must provide an implementation
} ShapeVTable;

typedef struct {
    const ShapeVTable *vtable;
} Shape;

// implemented method: shared by all subtypes
double shape_describe(const Shape *s) {
    return s->vtable->area(s);
}

typedef struct {
    Shape base;
    double r;
} Circle;

static double circle_area(const void *self) {
    const Circle *c = (const Circle *)self;
    return 3.14 * c->r * c->r;
}

// Circle's vtable: provides the area implementation
static const ShapeVTable circle_vtable = { circle_area };

int main(void) {
    Circle c = { { &circle_vtable }, 2 };
    printf("Area is %.2f", shape_describe((Shape *)&c));
    return 0;
}
Output
Area is 12.56

C++ C++26

C++26
#include <cstdio>
#include <string>
class Shape { // abstract class: has pure virtual functions, cannot be instantiated
public:
    virtual double area() const = 0; // pure virtual function: no body
    std::string describe() const {   // abstract classes may contain implemented methods
        char buf[64];
        std::snprintf(buf, sizeof buf, "Area is %.2f", area());
        return buf;
    }
    virtual ~Shape() = default; // polymorphic base class convention: virtual destructor
};
class Circle : public Shape {
    double r;
public:
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14 * r * r; }
};
int main() {
    Circle c(2);
    std::printf("%s\n", c.describe().c_str());
    return 0;
}
Output
Area is 12.56

C# v11.0.100

v11.0.100
// note: top-level statements must precede type declarations, so code runs first and types are declared afterwards
var s = new Circle(2);
Console.WriteLine(s.Describe());

abstract class Shape { // abstract class: cannot be instantiated directly
    public abstract double Area(); // abstract method has no body
    public string Describe() => $"Area is {Area()}"; // abstract classes may contain implemented methods
}
class Circle : Shape {
    private readonly double r;
    public Circle(double r) { this.r = r; }
    public override double Area() => 3.14 * r * r;
}
Output
Area is 12.56

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go has no abstract classes: interfaces constrain behavior, embedding reuses code
type Shape interface {
    Area() float64
}

type BaseShape struct{} // "base class" providing shared logic

func (BaseShape) Describe(a float64) string {
    return fmt.Sprintf("Area is %.2f", a)
}

type Circle struct {
    BaseShape // obtain Describe via embedding
    r         float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.r * c.r
}

func main() {
    var s Shape = Circle{r: 2}
    c := s.(Circle)
    fmt.Println(c.Describe(s.Area()))
}
Output
Area is 12.56

Java v27.0.1

v27.0.1
public class Main {
    abstract static class Shape { // abstract class: cannot be instantiated directly
        abstract double area(); // abstract method: subclasses must implement
        String describe() {    // abstract classes may contain implemented methods
            return "Area is " + area();
        }
    }
    static class Circle extends Shape {
        private final double r;
        Circle(double r) { this.r = r; }
        @Override
        double area() { return 3.14 * r * r; }
    }
    public static void main(String[] args) {
        Shape s = new Circle(2);
        System.out.println(s.describe());
    }
}
Output
Area is 12.56

JavaScript v26.13.1

v26.13.1
// JS has no native abstract class: convention is throwing in the constructor to block direct instantiation
class Shape {
    constructor() {
        if (new.target === Shape) {
            throw new Error("Shape is abstract and cannot be instantiated directly");
        }
    }
    area() {
        throw new Error("abstract method area must be implemented by subclasses");
    }
    describe() {
        return `Area is ${this.area()}`;
    }
}
class Circle extends Shape {
    constructor(r) {
        super();
        this.r = r;
    }
    area() {
        return (3.14 * this.r * this.r).toFixed(2);
    }
}
const s = new Circle(2);
console.log(s.describe());
Output
Area is 12.56

PHP v8.6.0

v8.6.0
abstract class Shape { // abstract class: cannot be instantiated directly
    abstract public function area(): float; // abstract method has no body
    public function describe(): string {   // abstract classes may contain implemented methods
        return "Area is " . $this->area();
    }
}
class Circle extends Shape {
    public function __construct(private float $r) {}
    public function area(): float {
        return 3.14 * $this->r * $this->r;
    }
}
$s = new Circle(2);
echo $s->describe();
Output
Area is 12.56

Python v3.15.2

v3.15.2
from abc import ABC, abstractmethod

class Shape(ABC):  # inherit ABC to become an abstract base class
    @abstractmethod
    def area(self):  # abstract method: subclasses must implement
        ...

    def describe(self):  # abstract classes may contain implemented methods
        return f"Area is {self.area()}"

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14 * self.r * self.r

s = Circle(2)
print(s.describe())
# instantiating Shape() directly raises TypeError
Output
Area is 12.56

Rust v1.99.1

v1.99.1
// Rust has no abstract classes: methods declared without a body in a trait are "abstract methods"
trait Shape {
    fn area(&self) -> f64; // no body: implementors must provide one

    fn describe(&self) -> String { // trait default method: reusable logic
        format!("Area is {:.2}", self.area())
    }
}

struct Circle {
    r: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.14 * self.r * self.r
    }
}

fn main() {
    let s = Circle { r: 2.0 };
    println!("{}", s.describe());
}
Output
Area is 12.56

TypeScript v26.13.1

v26.13.1
// TS natively supports abstract classes and abstract methods
abstract class Shape {
    abstract area(): number; // abstract methods have no body; subclasses must implement them
    describe(): string {     // abstract classes may contain implemented methods
        return `Area is ${this.area()}`;
    }
}
class Circle extends Shape {
    private r: number; // note: parameter-property syntax (constructor(private r)) needs the full TS compiler, so fields are declared explicitly here
    constructor(r: number) {
        super();
        this.r = r;
    }
    area(): number {
        return Number((3.14 * this.r * this.r).toFixed(2));
    }
}
const s = new Circle(2);
console.log(s.describe());
Output
Area is 12.56

Language differences

C: no classes — the example uses the struct + function-pointer vtable idiom (OOP-in-C), with semantics enforced by convention.

Go: no abstract classes — interfaces constrain behavior and embedded types reuse code (BaseShape plays the base-class role in the example), but embedding is not virtual dispatch — the embedded base cannot call back into the embedding type's implementations (no template-method hook).

JavaScript: no native abstract classes — conventions such as a new.target check or throwing from abstract methods are used instead.

PHP: uses the abstract keyword — an abstract class cannot be instantiated and may contain both abstract methods (no body) and implemented methods.

Python: uses abc.ABC + @abstractmethod (the same mechanism as the interface entry).

Rust: no abstract classes either — unimplemented trait methods are equivalent to abstract methods, and default methods reuse logic.

TypeScript: natively supports abstract classes and methods.