Dart Inheritance : Checking an Objects Type at runtime

Dart Inheritance : Checking an Objects Type at runtime

·

1 min read

Checking an Objects Type at runtime

  • Dart provides the is and as operators for checking an object's type at runtime.

  • This is useful when you need to perform different actions based on the actual type of an object.

  • Example :

  •   class ob {
          void makeSound() {
              print('Some generic sound');
          }
      }
    
      class Dog extends Ob {
          void bark() {
              print('Woof woof!');
          }
      }
    
      class Cat extends Ob {
          void meow() {
              print('Meow');
          }
      }
    
      void main() {
          Ob dog = Dog();
          Ob cat = Cat();
    
          if(dog is Dog) {
              print('dog is of type Dog');
          } else if (dog is cat) {
              print('dog is of type Cat');
          }
    
          if(cat is Dog) {
              print('cat is of type Dog');   
          } else if (cat is Cat) {
              print('cat is of type Cat');
          }
      }
    
  •   dog is of type Dog
      cat is of type Cat
    
      Exited.