상속과 인터페이스
코드 재사용을 위해 상속을 활용하고 더 나은 모듈화를 위해 인터페이스로 명확한 계약 API를 정의합니다.
상속과 인터페이스은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Inheritance?
In Solidity, inheritance allows one smart contract (the child) to reuse code, functions, and state variables from another contract (the parent). This is a fundamental concept in object-oriented programming.
- It promotes code reusability.
- It helps organize complex contract logic.
- It allows for modular and extensible designs.
Basic Inheritance Syntax
To make a contract inherit from another, you use the is keyword. The child contract gets access to all public and internal members of the parent contract.
Think of it like a child inheriting traits from its parent.
pragma solidity ^0.8.0;
contract ParentContract {
uint public parentValue;
constructor() {
parentValue = 100;
}
function getParentValue() public view returns (uint) {
return parentValue;
}
}
contract ChildContract is ParentContract {
// ChildContract inherits parentValue and getParentValue()
}Inheriting Functions & State
When ChildContract inherits from ParentContract, it automatically gains access to parentValue and the getParentValue() function. You can directly interact with them from the child contract.
Let's deploy ChildContract and see its parent's value!
pragma solidity ^0.8.0;
contract ParentContract {
uint public parentValue;
constructor() {
parentValue = 100;
}
function getParentValue() public view returns (uint) {
return parentValue;
}
}
contract ChildContract is ParentContract {
function getMyParentValue() public view returns (uint) {
return getParentValue(); // Calling an inherited function
}
function getDirectParentValue() public view returns (uint) {
return parentValue; // Accessing an inherited state variable
}
}Overriding Functions
Sometimes, a child contract needs to provide its own implementation for a function that already exists in the parent. This is called overriding.
To override a function:
- The parent function must be marked with
virtual. - The child function must be marked with
override. - Function signatures (name, parameters, return types) must match exactly.
Override Example
Here, the ChildContract provides a new behavior for greet(). Notice the virtual and override keywords.
pragma solidity ^0.8.0;
contract GreeterParent {
function greet() public virtual view returns (string memory) {
return "Hello from Parent!";
}
}
contract GreeterChild is GreeterParent {
function greet() public override view returns (string memory) {
return "Hello from Child!";
}
}Calling Parent Functions with 'super'
When you override a function, you don't always have to completely replace its logic. You can still call the parent's version of the function within the overriding function using super.
This is useful for extending or modifying parent behavior instead of replacing it entirely.
pragma solidity ^0.8.0;
contract Base {
function foo() public virtual pure returns (string memory) {
return "Base foo";
}
}
contract Derived is Base {
function foo() public override pure returns (string memory) {
string memory baseMessage = super.foo(); // Call parent's foo()
return string(abi.encodePacked(baseMessage, " and Derived logic"));
}
}What are Interfaces?
A Solidity Interface is like a blueprint or a contract without any implementation. It defines the public functions that a contract must have if it claims to implement that interface.
- They specify what functions exist and their parameters/return types.
- They do not contain any function bodies or state variables.
- All functions in an interface are implicitly
external.
Interface Syntax & Purpose
Interfaces are declared using the interface keyword. They are crucial for:
- Standardization: Ensuring contracts adhere to specific public APIs (e.g., ERC-20 token standard).
- Interoperability: Allowing contracts to interact with other contracts without knowing their full implementation details, only their interface.
- Modularity: Decoupling contract designs.
pragma solidity ^0.8.0;
interface ICalculator {
function add(uint a, uint b) external pure returns (uint);
function subtract(uint a, uint b) external pure returns (uint);
}Implementing an Interface
A contract can implement an interface using the is keyword, similar to inheritance. When a contract implements an interface, it must provide concrete implementations for all functions declared in that interface.
pragma solidity ^0.8.0;
interface IGreeter {
function greet() external view returns (string memory);
function setGreeting(string calldata _greeting) external;
}
contract MyGreeter is IGreeter {
string private currentGreeting = "Hello, World!";
function greet() public view override returns (string memory) {
return currentGreeting;
}
function setGreeting(string calldata _greeting) public override {
currentGreeting = _greeting;
}
}Quick Check: Inheritance vs. Interface
Which of the following statements about Solidity inheritance and interfaces is TRUE?
Recap: Inheritance & Interfaces
We've explored two powerful concepts in Solidity for building modular and reusable smart contracts:
- Inheritance: Allows a child contract to reuse code and logic from a parent using the
iskeyword. Functions can bevirtualin the parent andoverridein the child, andsupercan call parent logic. - Interfaces: Define a contract's public API without implementing its logic. They use the
interfacekeyword and ensure contracts adhere to specific function signatures, promoting standardization and interoperability.
Mastering these patterns is key to writing robust and maintainable Solidity code!
자주 묻는 질문
“상속과 인터페이스” 강의는 무료인가요?
네 — “상속과 인터페이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“상속과 인터페이스”에서 뭘 배우나요?
코드 재사용을 위해 상속을 활용하고 더 나은 모듈화를 위해 인터페이스로 명확한 계약 API를 정의합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“상속과 인터페이스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.