Solidity 作为以太坊智能合约的编程语言,支持面向对象编程(OOP)的核心概念,尽管实现方式与传统OOP语言有所不同。以下是Solidity中的主要OOP概念:
1. 合约(Contracts) - 类(Classes)的等价物

在Solidity中,合约类似于其他语言中的类:
-
合约是基本构建块,包含状态变量和函数
-
可以继承其他合约
-
可以被实例化(部署)
contract Vehicle {
// 状态变量(属性)
string public model;
uint public year;
// 构造函数
constructor(string memory _model, uint _year) {
model = _model;
year = _year;
}
// 方法
function getAge() public view returns (uint) {
return 2023 - year;
}
}
2. 继承
Solidity支持单继承和多级继承:
-
使用
is关键字 -
可以继承多个合约(多重继承)
-
支持函数重写(需要使用
virtual和override关键字)
contract Car is Vehicle {
uint public doorCount;
constructor(
string memory _model,
uint _year,
uint _doorCount
) Vehicle(_model, _year) {
doorCount = _doorCount;
}
}
3. 封装
Solidity通过可见性修饰符实现封装:
-
public- 任何人都可以访问 -
private- 仅当前合约内部 -
internal- 当前合约和继承合约 -
external- 仅能从外部调用
4. 多态
通过函数重写实现:
-
基类函数标记为
virtual -
派生类函数标记为
override
contract Animal {
function speak() public pure virtual returns (string memory) {
return "Sound";
}
}
contract Dog is Animal {
function speak() public pure override returns (string memory) {
return "Bark";
}
}
5. 抽象合约和接口
-
抽象合约:至少包含一个未实现的函数(标记为
abstract) -
接口:类似于抽象合约,但不能包含任何实现
abstract contract Logger {
function log(string memory message) public virtual;
}
interface IERC20 {
function transfer(address to, uint amount) external returns (bool);
}
6. 库(Libraries)
可重用的代码模块,类似于静态工具类:
-
不存储状态
-
不能继承或被继承
-
不能接收以太币
library Math {
function add(uint a, uint b) internal pure returns (uint) {
return a + b;
}
}
Solidity的OOP实现虽然有其特殊性(如合约部署、gas成本考虑等),但这些核心概念为智能合约开发提供了结构化和模块化的方法。
