Encapsulation does not seem to work in dart

27 Views Asked by At

I was of the thinking that once a variable is encapsulated, the values cannot be changed by a function or assignment outside its class.

However, in the below code, even after putting the underscore, the value of the String 'name' in the instance 'human' of the class 'Human' can be changed by adding an underscore.

void main() {
  
  Human human=Human();
  
  human._name='charles';
  
  print(human._name);
  
}

class Human{
  
String _name='Samuel';
int _age=20;
}

I was hoping that to encapsulate the String 'name' in the class Human,

void main() {
  
  Human human=Human();
  
  human._name='charles';
  
  print(human._name);
  
}

class Human{
  
String _name='Samuel';
int _age=20;
}
0

There are 0 best solutions below