Encapsulation is a technique for minimizing interdependencies among modules by defining a strict external communication. This way, internal coding can be changed without affecting the communication, so long as the new implementation supports the same (or upwards compatible) external communication.
Encapsulation prevents a program from becoming so interdependent that a small change has massive ripple effects.
The implementation of an object can be changed without affecting the application that uses it for:
Improving performance, fix a bug, consolidate code or for porting.
Access Specifiers:
In SystemVerilog, unqualified class properties and methods are public, available to anyone who has access to the object¿s name.
A member identified as local is available only to methods inside the class. Further, these local members are not visible within subclasses. Of course, nonlocal methods that access local class properties or methods can be inherited and work properly as methods of the subclass.
EXAMPLE: local variblg error class base;
localint i;
endclass
program main;
initial begin base b = new();
b.i = 123;
end endprogram
RESULT:
Local member 'i' of class 'base' is not accessible from scope 'main'
The above examples gives compilation error.
EXAMPLE: local varible access using method class base;
localint i;
task set(int j);
i = j;
$display(i);
endtask endclass
program main;
initial begin base b = new();
b.set(123);
end endprogram
RESULT
123
EXAMPLE: local varible access in subclass class base;
localint i;
endclass
class ext extends base;
function new();
i = 10;
endfunction endclass RESULT
Local member 'i' of class 'base' is not accessible from scope 'ext'
A protected class property or method has all of the characteristics of a local member, except that it can be inherited; it is visible to subclasses.
EXAMPLE: protected varible class base;
protectedint i;
endclass
class ext extends base;
function new();
i = 10;
endfunction endclass
EXAMPLE: protected varible in 2 level of inheritence class base;
localint i;
endclass
class ext extends base;
protectedint i;
endclass
class ext2 extends ext;
function new();
i =10;
endfunction endclass
In the above example, the varible i is overloaded in subclass with different qualifier.
EXAMPLE: Error access to protected varible. class base;
protectedint i;
endclass
program main;
initial begin base b = new();
b.i = 123;
end endprogram
RESULT
Protected member 'i' of class 'base' is not accessible from scope 'main'
Within a class, a local method or class property of the same class can be referenced, even if it is in a different instance of the same class.
A strict interpretation of encapsulation might say that other.i should not be visible inside of this packet because it is a local class property being referenced from outside its instance. Within the same class, however, these references are allowed. In this case, this.i shall be compared to other.i and the result of the logical comparison returned.