State variables in Solidity can be defined as public or private by using those respective keywords. A private variable isn’t a hidden or encrypted variable, but it can only be modified or “seen” by the contract that creates it. Here is an example of a public and private variable in Solidity:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
contract privateExample{
string public name = "Tom";
uint private age = 30;
function getName() public view returns(string memory){
return name;
}
function getAge() public view returns(uint){
return age;
}
}
contract privateExample2 is privateExample{
function getName2() public view returns(string memory){
return name;
}
function getAge2() public view returns(uint){
return age;
}
}
First off, private variables aren’t private. Anyone who has access to a blockchain explorer or knows how to look at transactions on a blockchain can simply read them. The real meaning of the “private” keyword, when applied to a variable is that it cannot be modified from an external contract.
Secondly, you’ll see in the contract above that attempting to read a private variable from another contract, even one that it inherits, will throw an error in your compiler.