Dart: OOPS
A class without constructor
We use class keyword to create a class in Dart. Static Variables which live on the class should be marked with static keyword. Instance Variables and Instance Methods live on the object. this keyword inside an instance method points to the object itself, hence we can access a property of the object.
A class with a constructor
A constructor is an instance method that is invoked when an object is created from the class. This is a good place to initialize instance variables. A constructor function has the same name as the class.
Getters and Setters
A combination of the getter and the setter methods are used to transform and/or encapsulate instance variables. In Dart, the getter is an instance method specified by get keyword. This method does not take any arguments, hence it does not contain parentheses (). While the setter method is specified by set keyword which receives value to be set as an argument.
Inheritance
A class has a constructor whose job is to set up initial instance variables. A class can also have methods. At times, some of our classes have common methods and common instance variables. Instead of maintaining two classes which have common functionalities, we can have one class inherit the functionality of the other class.
An interface is a blueprint or a template of a class. This blueprint contains definitions of instance variables and instance methods a class must implement. This is useful to enforce a consistent class structure.
Dart implicitly defines a class as an interface, hence called as implicit interface. To force a class to implement an interface, we use implements keyword just like extends keyword.
Polymorphism
Consider a situation where you have a method that takes an object of type Person or object of the type Employee which inherits from Person class. What Data Type of the parameter would you choose?
You could choose dynamic which represents everything but then you need to throw an exception if the argument is not of Person or Employee type. This is where Polymorphism saves us.

Comments
Post a Comment