ReasonJun

Solidity : class / object / method (object-oriented programming language) 본문

Blockchain/Solidity

Solidity : class / object / method (object-oriented programming language)

ReasonJun 2023. 10. 17. 15:48
728x90

Solidity is an object-oriented programming language, which means that it supports the concepts of classes, objects, and methods.

 

Class

A class is a blueprint for creating objects. It defines the structure and behavior of objects. A class can contain state variables, functions, and other classes.

 

Object

An object is an instance of a class. It has the state variables and functions defined in the class.

 

Method

A method is a function that belongs to a class. It can be used to modify the state of an object or to perform some other operation.

 

Example

The following code defines a simple class called Student:

contract Student {
    string public name;
    uint256 public age;

    constructor(string memory _name, uint256 _age) {
        name = _name;
        age = _age;
    }

    function getName() public view returns (string memory) {
        return name;
    }

    function getAge() public view returns (uint256) {
        return age;
    }
}

This class has two state variables: name and age. It also has two methods: getName() and getAge().

To create a new Student object, we can use the following code:

Student student = new Student("Alice", 18);

This will create a new Student object with the name "Alice" and the age 18.

We can then call the getName() and getAge() methods on the student object to get its name and age:

string memory name = student.getName();
uint256 age = student.getAge();

Benefits of using classes, objects, and methods in Solidity

There are a number of benefits to using classes, objects, and methods in Solidity:

  • Improved code organization: Classes, objects, and methods can help to improve the organization of your code by making it easier to group related functionality together.
  • Increased code reusability: Classes, objects, and methods can help to increase the reusability of your code by allowing you to create reusable components.
  • Improved code readability: Classes, objects, and methods can help to improve the readability of your code by making it clear which functions and data belong together.

Overall, classes, objects, and methods are powerful features of Solidity that can be used to improve the quality, readability, and reusability of your code.

728x90

'Blockchain > Solidity' 카테고리의 다른 글

Solidity : assert  (0) 2023.10.17
Solidity : encapsulation & hiding in OOP  (0) 2023.10.17
Solidity : Difference between 'abstract' and 'interface'  (1) 2023.10.17
Solidity : interface  (0) 2023.10.17
Solidity : abstract  (0) 2023.10.17
Comments