Home > Enterprise >  How to properly use Dart encapsulation in inheritance
How to properly use Dart encapsulation in inheritance

Time:08-07

Encapsulation says you should use private attributes, but this brought me an issue. I cannot access super-class attributes in my sub-class. I've readed that if classes are in different files, you cannot read them if their private, so should I just use public attributes or use multiple classes in the same file? which of this fixes are commonly accepted/not considered a bad practice?

class Animal{

  String? _color;
  String? _specie;
  int? _age;

  Animal(this._color, this._specie, this._age);

}
import 'Animal.dart';

class Dog extends Animal{

  bool? _rabid;

  Dog(super._color, super._specie, super._age, this._rabid);

  String? isRabid(){
    String isRabidMsg = 'is rabid?: $_rabid';
    return isRabidMsg;
  }

  String? sayAge(){
    String sayAgeMsg = "the age is: "; //Can't access age attribute from super-class
    return sayAgeMsg;
  }

}
void main() {
 Dog dog1 = new Dog('black', 'german shepard', 2, false);
}

CodePudding user response:

You could try and use getters for the private fields

class Animal {
 String? _color;
 String? _specie;
 int? _age;
 
 String? get color => _color;
 String? get specie => _specie;
 int? get age => _age
 
 ...
}
  • Related