What is the visibility of variables in Solidity?
Solidity is an object-oriented programming language for designing smart blockchain contracts.
Visibility of variables
Solidity offers programmers ways to select the visibility of variables within a contract based on the user's needs.
The visibility of variables can be set in three ways in Solidity:
- Public
- Private
- Internal
Let's discuss them in detail.
Public
The contract containing it and all the other smart contracts can access a public variable. We can create a getter for the public variable, but not any setter. The variable declared public cannot be modified externally.
Private
The contract can only access a private variable it resides within. No other contract can access or modify it.
Internal
The contract can only access an internal variable it was declared in or by the same contract’s derived contracts or subclasses.
Syntax
To define the visibility for any variable, we use the following syntax:
data_type visibility variable_name
- The
data_typecan beint,uint,string, etc. - The
visibilitycan bepublic,privateorinternal. - The
variable_nameis the name of the variable specified by the user.
Note: The
data_typealways comes before thevisibilityof the variable.
Code
pragma solidity ^0.5.0;/// defined contract Class Acontract Class_A{/// public member defined for Class Aint256 public A1;/// private member defined for Class Aint private A2 = 1;/// internal member defined for Class Aint internal A3 = 3;/// creating a constructor for Class Aconstructor() public {A1 = 2; // using a state variable}/// an internal function that returns the difference between the members A1 and A2function subtract() public view returns (int256){return A1 - A2;}/// an internal function that returns the sum between two numbers a and bfunction Add(int a, int b) internal pure returns (int){return a + b;}}/// defined contract Class B as child of Class Acontract Class_B is Class_A {/// a function that calls an internal function from Class Afunction Call_A_for_B() public view returns (int){/// used internal data member of Class Aint answer = Add(A3, 2);return answer;}}
Explanation
- Line 1: We use
pragmato specify the version of Solidity. - Line 7: We define a
publicmemberA1forClass_A. - Line 9: We define a
privatememberA2forClass_A. - Line 11: We define an
internalmemberA3forClass_A. - Lines 13–15: We declare a constructor for
Class_Awhere we specify the value for thepublicmemberA1. - Lines 17–19: We define a
publicfunction for subtracting the membersA1andA2ofClass A. - Lines 29–34: We define a function named
Call_A_for_B()and call the function defined inClass_Ainside it for addition. We pass theinternalmemberA3ofClass_Aas the argument.
Free Resources