Encapsulation in SystemVerilog: local, protected and public (Tested)
In short: Encapsulation means a class hides its data and lets the outside world change it only through the class’s own methods. In SystemVerilog, local members are visible only inside the class, protected members also in child classes, and everything else is public. The compiler enforces this, so a rule written once inside a method, like “no overdraw”, cannot be skipped.
A transaction with public fields is easy to write and easy to break. Any test can set a length of 300 on a 255-byte packet, and nobody finds out until the driver misbehaves.
In this lesson we start with a small bank account example, then go further with a UVM bench of 8 checks, and finally try to break the rules on purpose. I ran all of it on Synopsys VCS.
Start here: the simplest example
A bank account with a local balance and three public methods. The only way to change the balance is through deposit() and withdraw(), and withdraw() has a rule.
// tav_encap_simple.sv : the smallest encapsulation example (UVM 1.2 reporting only)
// The Art of Verification | theartofverification.com
// Run on Synopsys VCS X-2025.06-SP1 with UVM 1.2 (EDA Playground), 30 Nov 2026.
// EDA Playground: Synopsys VCS, UVM 1.2, top module "tav_top".
`include "uvm_macros.svh"
class tav_account;
local int tav_balance; // hidden: only this class can touch it
function void deposit(int amount); // public door in
tav_balance += amount;
endfunction
function bit withdraw(int amount); // public door out, with a rule
if (amount > tav_balance) return 0; // refused: not enough money
tav_balance -= amount;
return 1;
endfunction
function int get_balance(); // read-only view
return tav_balance;
endfunction
endclass
module tav_top;
import uvm_pkg::*;
tav_account a;
bit ok;
initial begin
a = new();
a.deposit(100);
`uvm_info("TAV_SIMPLE", $sformatf("1 deposit 100 : balance = %0d", a.get_balance()), UVM_NONE)
ok = a.withdraw(150);
`uvm_info("TAV_SIMPLE", $sformatf("2 withdraw 150 -> %0d : balance = %0d", ok, a.get_balance()), UVM_NONE)
ok = a.withdraw(30);
`uvm_info("TAV_SIMPLE", $sformatf("3 withdraw 30 -> %0d : balance = %0d", ok, a.get_balance()), UVM_NONE)
// a.tav_balance = 1000; // would not compile: tav_balance is local
end
endmodule
Here is what VCS printed:
UVM_INFO testbench.sv(34) @ 0: reporter [TAV_SIMPLE] 1 deposit 100 : balance = 100
UVM_INFO testbench.sv(36) @ 0: reporter [TAV_SIMPLE] 2 withdraw 150 -> 0 : balance = 100
UVM_INFO testbench.sv(38) @ 0: reporter [TAV_SIMPLE] 3 withdraw 30 -> 1 : balance = 70
- Line 2:
withdraw(150)returned 0 and the balance stayed 100. The rule inside the class said no. - Line 3:
withdraw(30)returned 1 and the balance dropped to 70.
The last line in the file is commented out. If you remove the //, the file stops compiling, and that is the whole point. We try it on purpose further down.
What you will learn
- What
local,protectedand public mean. - How methods guard the rules for your data.
- What a child class can and cannot touch.
- How
constand static members fit in. - What VCS says when code breaks the rules.
Cheat sheet: access levels
| Keyword | Inside the class | In a child class | Outside |
|---|---|---|---|
| (none), public | Yes | Yes | Yes |
protected | Yes | Yes | No |
local | Yes | No | No |
- Public is the default. Members with no keyword can be read and written by anyone.
constis a separate idea: aconstmember can be set once, innew(), and then only read.- Methods can be
localorprotectedtoo, for helpers nobody outside should call.
Analogy: a class is a bank branch. The vault is local, the back office is protected for staff, and the counter is public. Customers get money only through the counter, and the counter checks the rules.
Going further: one bench, 8 checks
tav_accounthas alocalbalance, aprotectedowner, aconstid and alocal staticcounter.tav_savingsextends it and adds interest, using only public methods for the balance.tav_cfgis a UVM config object whose setter refuses values outside 1 to 64.- Planted bug: the compile option
+define+TAV_BUGmakes the test write thelocalbalance directly.
Run it yourself: both files are on GitHub, with the expected output.
// tav_encap_uvm.sv : encapsulation in SystemVerilog, a complete working example (UVM 1.2)
// The Art of Verification | theartofverification.com
// Run on Synopsys VCS X-2025.06-SP1 with UVM 1.2 (EDA Playground), 30 Nov 2026.
// EDA Playground: Synopsys VCS, UVM 1.2, top module "tav_top".
// Paste this whole file into testbench.sv and leave design.sv empty.
//
// What is in here:
// tav_account local balance, protected owner, const id, local static counter, public methods
// tav_savings a child class: can use the protected owner, must go through methods for the balance
// tav_cfg a UVM config object whose setter refuses bad values
// tav_encap_test 8 self-checks, each printed with `uvm_info and checked with `uvm_error
//
// Options:
// (none) all 8 checks pass, 0 errors
// compile option +define+TAV_BUG the test writes a.tav_balance directly, so VCS refuses to compile
// (in EDA Playground, put +define+TAV_BUG in the "Compile Options" box)
`include "uvm_macros.svh"
package tav_encap_pkg;
import uvm_pkg::*;
`include "uvm_macros.svh"
// ---------------------------------------------------------------
// The account: data hidden, methods public
// ---------------------------------------------------------------
class tav_account;
local int tav_balance; // only tav_account can touch it
protected string tav_owner; // tav_account and its children
const int tav_id; // set once in new(), then read-only
local static int tav_count; // how many accounts exist, hidden
function new(string owner);
tav_owner = owner;
tav_count++;
tav_id = tav_count; // a const member may be set in the constructor
endfunction
function void deposit(int amount);
if (amount > 0) tav_balance += amount;
endfunction
function bit withdraw(int amount);
if (amount <= 0 || amount > tav_balance) return 0; // the rule lives in one place
tav_balance -= amount;
return 1;
endfunction
function int get_balance();
return tav_balance;
endfunction
static function int get_count();
return tav_count;
endfunction
endclass
// ---------------------------------------------------------------
// A child class
// ---------------------------------------------------------------
class tav_savings extends tav_account;
function new(string owner);
super.new(owner);
endfunction
function string get_tag();
return {"savings:", tav_owner}; // protected: allowed in a child
endfunction
function void add_interest();
deposit(get_balance() / 10); // local balance: only through the parent's methods
endfunction
endclass
// ---------------------------------------------------------------
// UVM: a config object that protects its own rule
// ---------------------------------------------------------------
class tav_cfg extends uvm_object;
`uvm_object_utils(tav_cfg)
local int tav_max_len = 16;
function new(string name = "tav_cfg");
super.new(name);
endfunction
function bit set_max_len(int v);
if (v < 1 || v > 64) begin
`uvm_warning("TAV_CFG", $sformatf("set_max_len(%0d) refused: allowed range is 1 to 64", v))
return 0;
end
tav_max_len = v;
return 1;
endfunction
function int get_max_len();
return tav_max_len;
endfunction
endclass
// ---------------------------------------------------------------
// The test
// ---------------------------------------------------------------
class tav_encap_test extends uvm_test;
`uvm_component_utils(tav_encap_test)
int tav_pass, tav_fail;
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction
function void tav_check(string what, string got, string exp);
if (got == exp) begin
tav_pass++;
`uvm_info("TAV_ENCAP", $sformatf("PASS %s: %s", what, got), UVM_LOW)
end
else begin
tav_fail++;
`uvm_error("TAV_ENCAP", $sformatf("FAIL %s: got %s, expected %s", what, got, exp))
end
endfunction
task run_phase(uvm_phase phase);
tav_account a;
tav_savings s;
tav_cfg cfg;
bit ok;
phase.raise_objection(this);
a = new("ravi");
// 1. The only way in is deposit()
a.deposit(100);
tav_check("1 balance after deposit(100)", $sformatf("%0d", a.get_balance()), "100");
// 2. The rule inside withdraw() refuses an overdraw
ok = a.withdraw(150);
tav_check("2 withdraw(150) result / balance", $sformatf("%0d / %0d", ok, a.get_balance()), "0 / 100");
// 3. A valid withdraw goes through
ok = a.withdraw(30);
tav_check("3 withdraw(30) result / balance", $sformatf("%0d / %0d", ok, a.get_balance()), "1 / 70");
// 4. A bad deposit is ignored by the class, not by every caller
a.deposit(-50);
tav_check("4 balance after deposit(-50)", $sformatf("%0d", a.get_balance()), "70");
`ifdef TAV_BUG
a.tav_balance = 1000000; // BUG: writes a local member from outside the class
`endif
// 5. A child can read a protected member
s = new("meera");
tav_check("5 s.get_tag() (protected owner)", s.get_tag(), "savings:meera");
// 6. A child reaches the local balance only through public methods
s.deposit(200);
s.add_interest();
tav_check("6 savings balance after interest", $sformatf("%0d", s.get_balance()), "220");
// 7. const id and the hidden static counter
tav_check("7 a.tav_id / s.tav_id / get_count()",
$sformatf("%0d / %0d / %0d", a.tav_id, s.tav_id, tav_account::get_count()), "1 / 2 / 2");
// 8. UVM config object: the setter refuses a bad value and keeps the old one
cfg = tav_cfg::type_id::create("cfg");
ok = cfg.set_max_len(100);
tav_check("8 set_max_len(100) result / value", $sformatf("%0d / %0d", ok, cfg.get_max_len()), "0 / 16");
`uvm_info("TAV_ENCAP", $sformatf("Checks: %0d pass, %0d fail", tav_pass, tav_fail), UVM_NONE)
phase.drop_objection(this);
endtask
endclass
endpackage
module tav_top;
import uvm_pkg::*;
import tav_encap_pkg::*;
initial run_test("tav_encap_test");
endmodule
How to run it
- Open EDA Playground and pick Synopsys VCS with UVM 1.2.
- Paste the file into
testbench.svand leavedesign.svempty. - Run it once with empty options.
- Put
+define+TAV_BUGin Compile Options and run again.
What VCS returned
| # | Check | Result | What it proves |
|---|---|---|---|
| 1 | Balance after deposit(100) | 100 | The public method is the way in |
| 2 | withdraw(150) result / balance | 0 / 100 | The rule refused an overdraw |
| 3 | withdraw(30) result / balance | 1 / 70 | A valid request goes through |
| 4 | Balance after deposit(-50) | 70 | One check in the class protects every caller |
| 5 | Child reads the protected owner | savings:meera | Children may use protected members |
| 6 | Child adds 10% interest to 200 | 220 | A local member is reached only through methods |
| 7 | a.tav_id / s.tav_id / get_count() | 1 / 2 / 2 | const ids set in new(), hidden static counter |
| 8 | set_max_len(100) result / value | 0 / 16 | The config object kept its old value and warned |
Result: 8 pass, 0 fail, plus the one UVM_WARNING that check 8 expects. Here is the log.
UVM_INFO @ 0: reporter [RNTST] Running test tav_encap_test...
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 1 balance after deposit(100): 100
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 2 withdraw(150) result / balance: 0 / 100
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 3 withdraw(30) result / balance: 1 / 70
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 4 balance after deposit(-50): 70
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 5 s.get_tag() (protected owner): savings:meera
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 6 savings balance after interest: 220
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 7 a.tav_id / s.tav_id / get_count(): 1 / 2 / 2
UVM_WARNING testbench.sv(88) @ 0: reporter [TAV_CFG] set_max_len(100) refused: allowed range is 1 to 64
UVM_INFO testbench.sv(115) @ 0: uvm_test_top [TAV_ENCAP] PASS 8 set_max_len(100) result / value: 0 / 16
UVM_INFO testbench.sv(170) @ 0: uvm_test_top [TAV_ENCAP] Checks: 8 pass, 0 fail
UVM_INFO /apps/vcsmx/vcs/X-2025.06-SP1//etc/uvm-1.2/src/base/uvm_objection.svh(1276) @ 0: reporter [TEST_DONE] 'run' phase is ready to proceed to the 'extract' phase
UVM_INFO /apps/vcsmx/vcs/X-2025.06-SP1//etc/uvm-1.2/src/base/uvm_report_server.svh(904) @ 0: reporter [UVM/REPORT/SERVER]
--- UVM Report Summary ---
** Report counts by severity
UVM_INFO : 12
UVM_WARNING : 1
UVM_ERROR : 0
UVM_FATAL : 0
** Report counts by id
[RNTST] 1
[TAV_CFG] 1
[TAV_ENCAP] 9
[TEST_DONE] 1
[UVM/RELNOTES] 1
The planted bug: the compiler says no
With +define+TAV_BUG, the test tries a.tav_balance = 1000000;. The simulation never starts. VCS stops at compile time:
Error-[SV-ICVA-L] Illegal class variable access
testbench.sv, 149
Local member 'tav_balance' of class 'tav_account' is not visible to scope
'tav_encap_test'.
Please make sure that the above member is accessed only from its own class
methods as it is declared as local.
Please refer to the SystemVerilog LRM (1800-2012) Section 8.18 Data hiding
and encapsulation.
1 error
CPU time: 4.451 seconds to compile
That error is encapsulation working. VCS names the member, the class and the scope that tried to touch it, and points to section 8.18 of the standard.
The lesson: make data local or protected when it has rules, and put the rules in methods. A broken rule then becomes a compile error, which is the cheapest bug you will ever fix.
Where encapsulation shows up in UVM
- Config objects: a setter can refuse bad values, as check 8 does, instead of every test checking them.
- Sequence items: constraints and
post_randomize()keep fields consistent, even when the fields stay public for randomization. - UVM base classes: many internal members are
localorprotected, which is why you call methods likeget_full_name()instead of reading fields.
Common mistakes to avoid
| Mistake | What you see | Fix |
|---|---|---|
Writing a local member from outside | Error-[SV-ICVA-L] at compile time | Call a method of the class |
Using local where children need access | The child class fails to compile | Use protected |
| Making everything public “for now” | Rules checked in some places, skipped in others | Hide data with rules behind methods from the start |
| A setter with no check | Bad values get in through the method | Validate inside the setter and return a status |
How AI helps you master this
- Find unguarded data: paste a class and ask which public fields have rules that nothing enforces.
- Write the setter: describe the legal range and ask for a setter that refuses bad values and reports them.
- Pick the keyword: paste a class tree and ask which members should be
localand whichprotected.
Warning: a convincing AI answer is not the same as a correct engineering result. If an AI tool says a child can read a local member, compile it and see.
Interview questions on encapsulation
- What is encapsulation? Hiding a class’s data and exposing it only through methods that enforce its rules.
- What is the difference between
localandprotected?localis visible only in the class itself.protectedis also visible in child classes. - What is the default access level? Public.
- When is the access check done? At compile time. The bug run never reached simulation.
- Can a
constmember be assigned in the constructor? Yes, once, innew(). After that it is read-only.
More practice: SystemVerilog interview questions.
Practice challenge
- Run the simple example, then remove the
//on its last line and read the error. - Run the full bench and confirm 8 pass, 0 fail.
- Change
tav_ownerfromprotectedtolocal. Which line fails to compile, and why? - Bonus: add a
withdraw_limittotav_accountthat a child may read but not change. Which keywords do you need?
FAQ
What is encapsulation in SystemVerilog? Keeping a class’s data hidden with local or protected, and letting other code change it only through the class’s methods.
What is the difference between local and protected? A local member is visible only inside its own class. A protected member is also visible in classes that extend it.
Are class members public by default in SystemVerilog? Yes. A member with no access keyword can be read and written from anywhere.
Why should I hide class data behind methods? So the rules for that data live in one place, and the compiler stops any code that tries to skip them.
Can a child class access a parent’s local member? No. It must use the parent’s public or protected methods, as tav_savings does in check 6.
How is encapsulation used in UVM? In config objects with checked setters, and inside the UVM base classes, which hide their internals and expose methods instead.
References
- IEEE 1800-2017, SystemVerilog standard: section 8.18 (data hiding and encapsulation), section 8.19 (constant class properties) and section 8.9 (static class properties).
Keep learning
- The OOP set: inheritance, polymorphism and the this keyword.
- Config in UVM: uvm_config_db and uvm_resource_db.
- Interview prep: SystemVerilog interview questions.
Part of the learning path SystemVerilog for verification

Hello sir I’m beginner in system verilog .please suggest some book sir.