I have two related classes: Animal and Cat (which extends Animal) then I make an instance of Cat and check if the instance is type Cat so I set amount of paws to four.
abstract class Animal {
}
class Cat extends Animal {
int? pawsAmount;
}
void main(List<String> arguments) async {
Animal barsik = Cat();
if (barsik is Cat) {
barsik.pawsAmount = 4;
}
}
and it works well BUT the follow code is not:
abstract class Animal {
}
class Cat extends Animal {
int? pawsAmount;
}
class Consumer {
Animal _animal;
Consumer(Animal animal) : _animal = animal;
void init() {
if (_animal is Cat) {
_animal.pawsAmount = 4;
}
}
}
void main(List<String> arguments) async {
Animal barsik = Cat();
if (barsik is Cat) {
barsik.pawsAmount = 4;
}
final consumer = Consumer(barsik);
consumer.init();
}
it has got an error:
bin/constest.dart:17:15: Error: The setter 'pawsAmount' isn't defined for the class 'Animal'.
- 'Animal' is from 'bin/constest.dart'.
Try correcting the name to the name of an existing setter, or defining a setter or field named 'pawsAmount'.
_animal.pawsAmount = 4;
^^^^^^^^^^
if I change
if (_animal is Cat) {
_animal.pawsAmount = 4;
}
to
if (_animal is Cat) {
(_animal as Cat).pawsAmount = 4;
}
it works fine
Is there any way to make the code work?
Thank you!