抽象类

演示抽象类与抽象方法;Go 用接口+组合、Rust 用 trait、JS 用约定替代。

C C23

C23
#include <stdio.h>

// "abstract class"惯用法:只暴露 vtable 接口;没有 vtable 就无法构造出有效的 Shape
typedef struct {
    double (*area)(const void *self); // 抽象方法:子类型必须提供实现
} ShapeVTable;

typedef struct {
    const ShapeVTable *vtable;
} Shape;

// 已实现方法:所有子类型共享
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 的 vtable:提供 area 实现
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;
}
输出
Area is 12.56

C++ C++26

C++26
#include <cstdio>
#include <string>
class Shape { // 抽象类:含纯虚函数,不能实例化
public:
    virtual double area() const = 0; // 纯虚函数:无函数体
    std::string describe() const {   // 抽象类可以包含已实现的方法
        char buf[64];
        std::snprintf(buf, sizeof buf, "Area is %.2f", area());
        return buf;
    }
    virtual ~Shape() = default; // 多态基类惯例:虚析构函数
};
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;
}
输出
Area is 12.56

C# v11.0.100

v11.0.100
// 注意:顶级语句必须位于类型声明之前,因此代码先执行、类型声明在后
var s = new Circle(2);
Console.WriteLine(s.Describe());

abstract class Shape { // 抽象类:不能直接实例化
    public abstract double Area(); // 抽象方法没有函数体
    public string Describe() => $"Area is {Area()}"; // 抽象类可以包含已实现的方法
}
class Circle : Shape {
    private readonly double r;
    public Circle(double r) { this.r = r; }
    public override double Area() => 3.14 * r * r;
}
输出
Area is 12.56

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go 没有抽象类:接口约束行为,嵌入复用代码
type Shape interface {
    Area() float64
}

type BaseShape struct{} // 提供共享逻辑的"基类"

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

type Circle struct {
    BaseShape // 通过嵌入获得 Describe
    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()))
}
输出
Area is 12.56

Java v27.0.1

v27.0.1
public class Main {
    abstract static class Shape { // 抽象类:不能直接实例化
        abstract double area(); // 抽象方法:子类必须实现
        String describe() {    // 抽象类可以包含已实现的方法
            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());
    }
}
输出
Area is 12.56

JavaScript v26.13.1

v26.13.1
// JS 没有原生抽象类:惯用法是在构造函数中抛错阻止直接实例化
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());
输出
Area is 12.56

PHP v8.6.0

v8.6.0
abstract class Shape { // 抽象类:不能直接实例化
    abstract public function area(): float; // 抽象方法没有函数体
    public function describe(): string {   // 抽象类可以包含已实现的方法
        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();
输出
Area is 12.56

Python v3.15.2

v3.15.2
from abc import ABC, abstractmethod

class Shape(ABC):  # 继承 ABC 成为抽象基类
    @abstractmethod
    def area(self):  # 抽象方法:子类必须实现
        ...

    def describe(self):  # 抽象类可以包含已实现的方法
        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())
# 直接实例化 Shape() 会抛 TypeError
输出
Area is 12.56

Rust v1.99.1

v1.99.1
// Rust 没有抽象类:trait 中只声明不带函数体的方法即"抽象方法"
trait Shape {
    fn area(&self) -> f64; // 无函数体:实现者必须提供

    fn describe(&self) -> String { // trait 默认方法:可复用逻辑
        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());
}
输出
Area is 12.56

TypeScript v26.13.1

v26.13.1
// TS 原生支持抽象类与抽象方法
abstract class Shape {
    abstract area(): number; // 抽象方法没有函数体,子类必须实现
    describe(): string {     // 抽象类可以包含已实现的方法
        return `Area is ${this.area()}`;
    }
}
class Circle extends Shape {
    private r: number; // 注意:参数属性语法(constructor(private r))需要完整 TS 编译器,这里改为显式声明字段
    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());
输出
Area is 12.56

语言差异说明

C:无类机制,示例为 struct + 函数指针 vtable 的 OOP-in-C 惯用法,语义由约定保证。

Go:无抽象类,以接口约束行为 + 内嵌类型复用代码(示例中 BaseShape 承担基类角色);但嵌入不是虚函数分派——被嵌入的基类无法回调外层类型的实现(无模板方法钩子)。

JavaScript:无原生抽象类,用 new.target 检查或抽象方法抛错来约定。

PHP:用 abstract 关键字:抽象类不能实例化、可同时包含抽象方法(无方法体)与已实现方法。

Python:用 abc.ABC + @abstractmethod(与接口条目同一套机制)。

Rust:无抽象类,trait 中不实现的方法等价于抽象方法,配合默认方法复用逻辑。

TypeScript:原生支持 abstract 类与抽象方法。