Variable visibility

In Solidity, state variable visibility is the access level of a state variable within a contract. It determines which functions can read and modify the variable. The visibility levels in Solidity are public, internal, and private.

The public state variables

These variables are accessible to all functions, external functions, and contracts. In Solidity, a public state variable automatically creates a getter method due to the compiler’s actions. This enables other contracts to access its value using the getter method. However, external contracts can’t directly change this public state variable because no setter method is autogenerated. Within the same contract, the variable’s value is read directly from storage.

The internal state variables

These variables are accessible to all functions within the contract. In Solidity, internal state variables are only accessible within the contract itself and derived contracts. These variables don’t automatically generate getter or setter methods, meaning external contracts can’t read or modify their values. When accessed within the contract or derived contracts, the variable’s value is read directly from storage.

The private state variables

In Solidity, private state variables are strictly accessible only within the contract where they’re declared. Unlike public variables, they don’t automatically generate getter methods, so no external contract can read their values. Also, they can’t be accessed even by derived contracts. When utilized within the declaring contract, the value is directly read from storage.

Example

The example below demonstrates how the setVars() function enables us to assign values to the publicVar, internalVar, and privateVar variables. It also illustrates the use of the getPublicVar(), getInternalVar(), and getPrivateVar() functions to retrieve the values of these respective variables.

Get hands-on with 1400+ tech skills courses.