Solidity is an object-oriented programming language for designing smart blockchain contracts.
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:
Let's discuss them in detail.
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.
The contract can only access a private
variable it resides within. No other contract can access or modify it.
The contract can only access an internal
variable it was declared in or by the same contract’s derived contracts or subclasses.
To define the visibility for any variable, we use the following syntax:
data_type visibility variable_name
data_type
can be int
, uint
, string
, etc. visibility
can be public
, private
or internal
. variable_name
is the name of the variable specified by the user.Note: The
data_type
always comes before thevisibility
of the variable.
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;}}
pragma
to specify the version of Solidity. public
member A1
for Class_A
.private
member A2
for Class_A
.internal
member A3
for Class_A
.Class_A
where we specify the value for the public
member A1
.public
function for subtracting the members A1
and A2
of Class A
.Call_A_for_B()
and call the function defined in Class_A
inside it for addition. We pass the internal
member A3
of Class_A
as the argument.Free Resources