The visibility of a state variable or a function defines who can see it. There are four kinds of visibilities for function and state variables: external, public, internal, and private.
By default, the visibility of functions is public and the visibility of state variables is internal. Let's look at what each of these visibility functions mean:
- external: External functions can be called only from other contracts or via transactions. An external function f cannot be called internally; that is, f() will not work, but this.f() works. You cannot apply the external visibility to state variables.
- public: Public functions and state variables can be accessed in all ways possible. The compiler generated accessor functions are all public state variables. You cannot create your own accessors. Actually, it generates only getters, not setters.
- internal: Internal functions and state variables can only be accessed internally, that is, from within the current contract and the contracts inheriting it. You cannot use this to access it.
- private: Private functions and state variables are like internal ones, but they cannot be accessed by the inheriting contracts.
Here is a code example to demonstrate visibility and accessors:
contract sample1
{
int public b = 78;
int internal c = 90;
function sample1()
{
//external access
this.a();
//compiler error
a();
//internal access
b = 21;
//external access
this.b;
//external access
this.b();
//compiler error
this.b(8);
//compiler error
this.c();
//internal access
c = 9;
}
function a() external
{
}
}
contract sample2
{
int internal d = 9;
int private e = 90;
}
//sample3 inherits sample2
contract sample3 is sample2
{
sample1 s;
function sample3()
{
s = new sample1();
//external access
s.a();
//external access
var f = s.b;
//compiler error as accessor cannot used to assign a value
s.b = 18;
//compiler error
s.c();
//internal access
d = 8;
//compiler error
e = 7;
}
}