A contract is like a class. A contract contains state variables, functions, function modifiers, events, structures, and enums. Contracts also support inheritance. Inheritance is implemented by copying code at the time of compiling. Smart contracts also support polymorphism.
Let's look at an example of a smart contract to get an idea about what it looks like:
contract Sample
{
//state variables
uint256 data;
address owner;
//event definition
event logData(uint256 dataToLog);
//function modifier
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
//constructor
function Sample(uint256 initData, address initOwner){
data = initData;
owner = initOwner;
}
//functions
function getData() returns (uint256 returnedData){
return data;
}
function setData(uint256 newData) onlyOwner{
logData(newData);
data = newData;
}
}
Here is how the preceding code works:
- At first, we declared a contract using the contract keyword.
- Then, we declared two state variables; data holds some data and owner holds the Ethereum wallet address of the owner, that is, the address in which the contract was deployed.
- Then, we defined an event. Events are used to notify the client about something. We will trigger this event whenever data changes. All events are kept in the blockchain.
- Then, we defined a function modifier. Modifiers are used to automatically check a condition prior to executing a function. Here, the modifier checks whether the owner of the contract is invoking the function or not. If not, then it throws an exception.
- Then, we have the contract constructor. While deploying the contract, the constructor is invoked. The constructor is used to initialize the state variables.
- Then, we defined two methods. The first method was to get the value of the data state variable and the second was a method to change the data value.
Before getting any further deeper into the features of smart contracts, let's learn some other important things related to Solidity. And then we will come back to contracts.