Categories
Dart

Dart Access Modifiers

Access modifiers or access specifiers (i.e, private, public and protected) are not supported in dart language.

Although to make any class or method private(i.e., access of that specific class or method to have scope limited to themselves only.) you have to start the function or class name using _.

For ex :

//_Test is a private class as we have defined it using _
class _Test{
//_Hello() is a private method as we have defined it using _
	_Hello(){
	}
}

Any Class or methods written in program are by default private in dart.

So there is no concept of access specifiers in dart language.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Exception Handling

Exception in a programming language is a termination of the program during execution.

Exception is an unwanted or unexpected event which interrupts the normal flow of the program execution.

Exception must be taken care to continue our program execution. Otherwise program or application gets terminated.

For ex :

void main(){
  	List games=new List();
	print("Exception Test");
	// Index out of range exception will occur due to no element will be found in the list at index as list is empty. Hence, further statements will not executed with the termination of the program.
  	print(games[5]);
	print("Exception Test");
}

Whenever an exception occurs, program gets terminated abnormally without executing remaining part of the program. That’s why we have to handle the exception.

What is Exception Handling?

Exception handling is a mechanism to solve or handle the runtime errors. There are different kinds of exceptions can strike based on which type of mistake you have made while writing your program. Like, IndexOutOfRangeException, IOException, NullPointerException etc.

Exception handling is the mechanism to handle unknown mistakes you made in your program to prevent program or application termination.

Dart have some concepts for handling exceptions smoothly as following,

  • try
  • on/catch
  • finally
  • throw

try

Block of code or statements which might result in an exception must be kept inside try block to throw generated exception.

Generated exception will be thrown to the on or catch block.

Syntax :

try{
            // block of code
}catch(e){
            // handle thrown exception
}

Try block must be followed by on or catch or finally block.

on/catch

On or catch block are used to handle the thrown exception from try block.

On or catch keywords can be used separately as well as together to catch an exception.

A try block can be followed by multiple catch blocks. Multiple catch blocks are used to handle different types of exceptions.

Syntax :

try{
            // code block
}
// to use on keyword it must be followed by the Exception that may occur. On should be used only when you definitely know that particular exception will occur from try block. Otherwise, catch will always handle your exceptions smoothly.
on ExceptionName catch(e){
            // code block
}

In above syntax, ExceptionName is the type of exception that may occur based on different situations. Like, ArithmaticException, IntegerDivisionByZeroException etc. can be thrown via try block if you made some mistake related to them.

finally

finally is a block used to perform certain operations whether exceptions take place in program or not.

finally is generally used to release the different resources requested during the operation. In general case, releasing database resources, closing opened files etc.

Syntax :

try{

}finally{
            //statements you want to perform
}

finally must have an associate try block.

For ex :

void main(){  
  try{
     List<String> games=new List();
    print(games[5]);
  }on IntegerDivisionByZeroException catch(e){
    print("Divide By Zero Error");
  }on IndexError catch(e){
    print("Handle Index Error");
  }finally{
    print("Release Resources.");
  }
}

Output :

Handle Index Error
Release Resources.

Throw

Throw keyword is used to manually throw the exception in programs.

Generally, it is used to terminate the program while some logical condition does not satisfies as per our requirement.

Syntax :

throw new ExceptionName();

Here ExceptionName is the exception you want to be thrown to terminate the program.

To solve the program termination due to exceptions thrown using throw keyword, use throw in try-catch block.

For ex :

void main(){
  int x=5,y=0;
  if(y==0){
	// throwing an exception
     throw new IntegerDivisionByZeroException();
  }else{
    print(x);
  } 
}

Output :

Uncaught exception: IntegerDivisionByZeroException

Mistakes can happen by any one. So exception can strike at any point in your program and the solution of our problem is exception handling. Hence, we have learned exceptions to take care our programs for better user experience.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Interface

Generally, dart interface is used for as a replacement for multiple inheritance.

In dart, interface has the similar structure as class. Interface in dart defined using class keyword.

So, you will think that how an interface is different than class in dart?

Actually, interface in dart has been removed and the concept of interface in dart is optional(like no significance meaning in dart).

In dart, all classes are implicit interfaces which means classes itself act as interface.

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

In dart, An interface is a class which can be inherited by another class using implements keyword.

Methods inside interface should have body in dart language.

Any class which implements the interface must have to implement all the methods of that particular interface.

For ex :

class ButtonClickListener{
	void onButtonClick(){
    print("Default Button Clicked !!");	
  }
}
class Login implements  ButtonClickListener{
// implement all the methods of  ButtonClickListener
	onButtonClick(){
		print("Login Button Clicked !!");	
	}
}
class Signup implements  ButtonClickListener{
// implement all the methods of  ButtonClickListener
  onButtonClick(){
		print("Signup Button Clicked !!");	
	}
}
void main(){
// you can create an object of a class which act as implicit interface
  ButtonClickListener listener=new ButtonClickListener();
  listener.onButtonClick();
  Login login=new Login();
  login.onButtonClick();
  Signup signup=new Signup();
  signup.onButtonClick();
}

Output :

Default Button Clicked !!
Login Button Clicked !!
Signup Button Clicked !!

As dart is an optionally typed language, we don’t need to use interfaces. Just by writing appropriate methods with proper signature in classes is enough to fulfill your requirements.

Personally, i don’t suggest to focus interface in dart labguage as they do not have special case in dart language.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Collection

Collections are the data structures(i.e., specialised format for storing and managing diffrent types of data) which are used to store and manipulate the group of obects.

general collections supported by dart are as below,

  • List
  • Map
  • Set

out of which list and map have been already covered in previous tutorials.

What is Set ?

Dart Set is a collection of unique objects or items.

Dart set is an unordered collection as it not allows you to add elements or items at particular index or position in the set.

So, traversing to different position or elements in set is difficult.

If you try to add any item in the set which is already present then it will not be inserted or stored in the set. Which means set doesn’t allow the duplicate entries while inserting.

Set Common Properties

For ex :

void main(){  
  Set languages=new Set<String>();
  languages.add("C");
  languages.add("C++");
  languages.add("Java");
  languages.add("Dart");
  languages.add("C++");
  languages.add("Java");
  
  Set humanLanguage=new Set<String>();
  humanLanguage.add("English");
  humanLanguage.add("Hindi");
  humanLanguage.add("Gujarati");
  humanLanguage.add("C++");
  humanLanguage.add("Java");
  
  //duplicate values not allowed in set
  print(languages.toSet());
  print(languages.toList());
  print(languages.length);
  
  print(humanLanguage.length);
  print(humanLanguage.toSet());
  
  print(humanLanguage.contains("English"));
  print(humanLanguage.remove("Hindi"));
  print(humanLanguage.union(languages));
  print(humanLanguage.intersection(languages));
  print(humanLanguage.difference(languages));
  humanLanguage.clear();
  print(humanLanguage.length);
}

Output :

{C, C++, Java, Dart}
[C, C++, Java, Dart]
4
5
{English, Hindi, Gujarati, C++, Java}
true
true
{English, Gujarati, C++, Java, C, Dart}
{C++, Java}
{English, Gujarati}
0

Set collection have many methods which makes your collection handy to use.

Set is generally used to make your collection having unique values of same data type.

Make yourself comfortable with collections like List, Map and Set to better understand the different data structures.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Abstraction

Abstraction is the process of providing the functionality or essential requirements and hiding the implementation details from users to reduce the complexity and effort.

The best real life example of Abstraction is ATM Machine. We perform many transaction operations in ATM Machine like money transfer, withdrawal, balance check etc. But, we doesn’t know the internal functionality of the ATM while we perform our different ATM transactions.

Abstraction in Dart can be achieved using Abstract Class.

before learning about abstract class it’s better to have a look at abstract methods.

Abstract Method

Methods declared without implementation and ends with semicolon are known as abstract methods.

They can be declared inside Abstract class only.

Any abstract methods declared inside particular class must be implemented or say overriden by the class which inherits that particular class.

Abstract Class

Abstract class must be declared using Abstract keyword.

They are useless until any concrete class (the class which is not abstract) inherits it.

If a class inherits the Abstract class then either it must implement all the methods of that abstract class or must be declared as abstract class.

Abstract class can have abstract methods as well as concrete methods(non-abstract methods).

Abstract class can not be instantiated as it may have abstract methods.

As abstract methods have no body. So, accessing abstract methods is useless as it isn’t have any implementation.

That’s why Abstract class is also refered as Incomplete class.

For ex :

If a car has not proper brakes working. Nobody will drive that unsafe and incomplete car to avoid accidents.

Similarly, Abstract keyword ensures that no one would be allowed to instantiate the instance of an Abstract class(incomplete class). Even if an Abstract class have only non-abstract methods.

Let’s understand the Abstraction with a more common Example .

Let say we want to create a program for the Animal Feed.

For Animal Feed program, we will need feedAnimal() method for each Animal.

So, it’s a better way to create an abstract method in an Abstract class. By making this method abstract we ensures that each class has a feed method.

For ex :

abstract class Animal {

// Abstract method feedback() with no body and ends with semicolon
  feedAnimal();

  sleepAnimal(){
    print("Sleeping...");
  }
}
class Cat extends Animal {
	feedAnimal(){
    print("Feed Cat") ;
  }
}
class Dog extends Animal {
	feedAnimal(){
    print("Feed Dog") ;
  }
}
class Fox extends Animal {
	feedAnimal(){
    print("Feed Fox") ;
  }
}
void main(){
	Animal c=new Cat();
	Animal d=new Dog();
	Animal f =new Fox();
	c.feedAnimal();
	d.feedAnimal();
	f.feedAnimal();
}

Output :

Feed Cat
Feed Dog
Feed Fox

For this program, we have created a super abstract class Animal with abstract method feedAnimal().

Now, each subclass of Animal class must have to implement the abstract method feedAnimal() of the Abstract class Animal.

This way we ensure that all the classes who are the subclasses of the Animal class must have the feedAnimal() method.

So Abstraction is defining characteristics for Animal class that each Animal must be feeded. How each Animal is feeded is implemented in the classes which inherits Animal class and hidden from the user.

So, Abstraction is the process of showing the essential details and hiding internal implementation process.

You can have upper hand on Abstraction by practicing it more and more.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Polymorphism

Polymorphism is one of the four fundamental concept for learning object oriented programming.

The word polymorphism has been derived from 2 greek words “poly” and “morph” where poly means many and morph means form.

Polymorphism means an object have different forms and each different form performs same action/task in multiple/different ways.

Polymorphism is generally used to achieve the inheritance mechanism.

Let’s see polymorphism with real word example,
Tony can speak three languages i.e., Gujarati, Hindi and English.

Now Tony will speak Gujarati language with the person who knows Gujarati. Similarly, tony will speak English with the person who knows English and speaks Hindi with the person who knows Hindi.

Here Tony perform one single task that is Speaking. But, the implementation of speaking is different based on language tony speaks. Here, speaking can be in three forms.

So here Tony is the object of the class and speaking is the polymorphism.

Polymorphism in dart is supported only in form of runtime polymorphism (For ex : method overriding etc).

Here we need to understand some concepts before learning polymorphism which are

  • Up-Casting
  • Down-Casting

Up-Casting

Up-Casting is the process of converting a reference of the subclass type to the super class type.

However converting the reference of subclass to superclass will not convert the object to its super type.

It just converts the child object to a more general form(base form) or say it treats the child object as super object.

For ex :

class Shape
{
}

class Triangle extends Shape
{
}

void main()
{
	// Up-casting
	Shape s=(Shape) new Triangle();
	// It is same as Shape s=(Shape) new Triangle();
	Shape s=new Triangle();     
        // Up-casting is done automatically via system.
}

Down-Casting

Down-casting is the process of converting a reference of the superclass type to the sub class type.

Down-casting needs to be done manually by programmer.

For ex :

void main()
{
        // here runtime type of a is Triangle()
	Animal anim=new Triangle();	
	Triangle tri=a;
}

Down-casting is casting the superclass object reference to subclass reference.

Down-casting can be done only if the runtime type of the superclass (i.e., anim’s runtime type is Triangle) must be to the specific subclass reference(i.e., tri’s runtime type is Triangle) in which we are Down-casting.

For ex :

void main()
{
	// here runtime type of a is Animal()
	Animal anim=new Animal();	
	Triangle tri=a;
}

Here runtime type of superclass reference doesn’t match with the subclass reference in which we are Down-casting. Which will generate ClassCastException.

That’s why Up-casting is safer than Down-casting as it is done automatically.

Up-casting and Down-casting both are done at runtime.

Unlike other object oriented programming languages, Dart only supports runtime polymorphism(for ex : function overriding)

Runtime Polymorphism

Runtime polymorphism is the process of calling the overridden function at runtime(at the time of program execution) instead of compile time.

Let’s take an example to understand the polymorphism in better way.

Suppose, we want to draw shapes for different classes. So, we’ll create a class Shape with method drawShape() which draws a Circle Shape.

Let’s create a Shape class which has a method drawShape().

class Shape
{
            drawShape()
        {
                        print(” Circle Shape”);
            }
}

Now there are 3 more sub-classes Triangle, Square and Hexagon of Shape class. All these subclasses will call drawMethod() to draw circle shape.

Now, you will be thinking why we’re creating a Parent class shape and creating a method drawShape() in it.

Because it’s a better way to create a one single method drawShape() and access that method from each classes who wants to draw shape instead of writing that method in each class(writing the same method will consume your memory as well as time).

That’s why we will use the reusability concept of inheritance.

For ex :

class Shape
{
	drawShape()
        {
		print(" Circle Shape");
	}
}
class Triangle extends Shape
{
}
class Square extends Shape
{
}
class Hexagon extends Shape
{
}
void main(){
// Upcasting
	Shape T=new Triangle();
	Shape S=new Square();
	Shape H=new Hexagon();

	T.drawShape();
	S.drawShape();
	H.drawShape();
}

Output :

Circle Shape
Circle Shape
Circle Shape

Now, if triangle class don’t want to draw circle shape from its super class. So, what we can do is that we’ll create a drawShape() method in Triangle class with its own implementation.

For ex :

class Shape
{
	drawShape()
        {
		print(" Circle Shape");
	}
}

class Triangle extends Shape
{
	drawShape()
        {
		print("Triangle Shape");
	}
}
class Square extends Shape
{
}
class Hexagon extends Shape
{
}
void main()
{
        // Upcasting
	Shape T=new Triangle();
	Shape S=new Square();
	Shape H=new Hexagon();

	T.drawShape();
	S.drawShape();
	H.drawShape();
}

Output :

Triangle Shape
Circle Shape
Circle Shape

So in above class when you called the method with the object of class Triangle T, it will first check the method drawShape() in Triangle class. If it’s present then drawShape() method from class Triangle will be implemented else it will check for the accessible drawShape() method in its superclass Shape.

If it’s present in Shape class then drawShape() method of Shape will be executed else it will further check for the accessible drawShape() method in its Super class.

This process will be continued till either the required method drawShape() is found or the highest super class is reached.

This process is known as method overriding.

Polymorphism is the process in which the output of your program depends on the inputs you provide.

For ex :
In above case, the drawShape() method of which class will be depends on the object of particular class accesses it.

So explore more cases of polymorphism by performing some critical programs and practice it to make your development code more convenient to use.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Inheritance

Dart supports Inheritance which is one of the core concept of the object oriented programming language.

Inheritance mechanism is used to consume properties and behaviour of a super class in subclass.

Inheritance is the concept by which one class can derive properties and methods of another class.

The class which derives or inherits the properties from another class is known as child class or Sub Class.

The class whose properties are derived or inherited by other classes is known as parent class or super class.

In Inheritance, child class has access to the properties and methods of its own class as well as its parent class.

In dart, Object class is the Super class of all classes. Hence, each class is derived from at least one class or have at lease one parent class except Object class.

In Dart, extends keyword is used for Inheritance.

There are 2 types of inheritance in dart.

  1. Single Inheritance
  2. Multilevel Inheritance

Single Inheritance

when properties and methods of one class is derived from exact one other class is known as Single Inheritance.

For ex :

class A{
	displayA(){
		print("A");
	}
}
class B extends A{
	displayB(){
		print("B");
	}
}

void main(){
	A a=new A();
	B b=new B();
	a.displayA();
	b.displayA();
	b.displayB();
}

Output :

A
A
B

In Above example, class B has all the properties and methods of its parent class A as well itself.

Multilevel Inheritance

Multilevel Inheritance is the type of inheritance in which a class can be derived from another derived class. i.e., A class will act as the Super class for any particular class and that same class will act as the child class for another class.

For ex :

class A{
  displayA(){
    print("A");
  }
}
class B extends A{
  displayB(){
    print("B");
  }
}
class C extends B{
  displayC(){
  }
}
void main(){
  A a=new A();
  B b=new B();
  C c=new C();
  a.displayA();
  b.displayA();
  b.displayB();
  c.displayA();
  c.displayB();
  c.displayC();
}

Output :

A
A
B
A
B

In above example, class B is derived from class A. So, class B acts as the child or sub class for class A.

Similarly, class C is derived from class B. That’s why class B acts as the parent class or super class for class C.

Also, one point to note down is that the child class will have access to the properties of its immidiate parent class as well as all its non immidiate parent classes.

Output :

class C have access to all the properties and functions of its immidiate parent class B as well as its non immidiate super parent class A.

We also need to understand the code reusability as it is the main purpose of the Inheritance

Code Reusability

It is nothing but accessing or using the properties and methods of existing class while creating a new class as per user requirement.

This concept is used to remove redundant or duplicate code written in the program for optimizing your coding skills and program structure.

Code Reusability can be easily achieved using the inheritance.

For ex :

class Favourite{
  int rank=5;
  Test(){
    print("This is Test Method");
  }
	Calculation(int a,int b){
		print(a+b);
	}
}
class Normal extends Favourite{
  
}
void main(){
	Normal normal=new Normal();
  	normal.Test();
 	print(normal.rank);
  	normal.Calculation(5,10);
}

Output :

This is Test Method
5
15

In above example, class Normal doesn’t have any properties or methods, but it can access all the properties and methods of its super class using Inheritance.

let say, if we define Calculation() function in class Favourite and further we also need Calculation() function in Normal class. So, if Normal class inherits the Favourite class then using Inheritance rules we do not need to define that function again in Normal class.

As all the properties and functions of parent class are also the properties and functions of its child class. Just as you’re parents’ property is yours too.

So, for enhancing the code structure and reusability of your code the Inheritance concept is widely used.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Static Variables and Methods

Class is a template or prototype (or say defined model or structure) from which objects (instances) are created. Each instance of class have properties (variables) and behaviours (methods) defined in the prototype class. The scope of instance variables and methods are limited to particular instance’s lifetime only. So, it’s not possible to access or share a single variable to all the instances of a class using instance variables and instance methods etc.

Static Variables and Methods

Static variables and methods are mostly used to store information which can be shared among all the instances of class.

They are initialized only once, at the start of the program execution. Class variables and methods are initialized even before the instance variables or objects of the class.

Static Variables and methods are known as class variables and methods.

To declare a static variable or method static keyword is used in the program.

Static Variable Syntax :

static dataType varaiableName;

Static Methods Syntax :

static returnType methodName(){

// code block

}

Static variables and methods can’t be accessed creating instance of a class.

To access static variables and methods, call them with the className(in which particular static variable or method is declared).

For ex :

class SetTopBox{
  static String Channel;
  static changeChannel(String channelName){
    print("Change Channel : " + channelName);
  }
}
void main(){
// calling static variable Channel using className following . followed by variableName.
  SetTopBox.Channel="Sony TV";  
// calling static method changeChannel using className following . followed by methodName.
 print(SetTopBox.Channel);
  SetTopBox.changeChannel("Star TV");
}

Output :

Sony TV
Change Channel : Star TV

We can also share a static variable or method among different classes as well. To access a static variable or method from other class we need to call them using the className in which they are declared.

For ex :

class SetTopBox{
  static String Channel="Cartoon TV";
  static changeChannel(String channelName){
    print("Change Channel : " + channelName);
  }
}
class AndroidTV{
  AndroidTV(String channelName){
    print(SetTopBox.Channel);
    SetTopBox.changeChannel(channelName);
  }
}

void main(){
  AndroidTV TV=new AndroidTV("Discovery TV");
}

Output :

Cartoon TV
Change Channel : Discovery TV

In this way, we can easily share a variable and method across all the classes of our large projects. Which in turn makes our programming way more easy to handle and manipulate the data.

You must be well aware about static variables and methods for a better programming experience in your different projects.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Instance Variable vs Reference Variable

Instance variables and reference variables are very useful concepts of object oriented programming structure to deeply understand the class and object concept.

So let’s get started with instance variable.

What is Instance Variable ?

Instance variable is a variable declared inside the class but outside any function(method) or any block of code.

Basically, instance variables are the properties of class. every object of a particular class has  individual copy of all instance variables.

Instance variables are created with object creation and gets destroyed with object destruction.

The scope of instance variables differs from object to object of particular class. Which means each copy of instance variables belongs to particular object of that class.

For ex :

class Avengers{
  int rank;
  String Name;
  Avengers(int avengerRank,String avengerName){
    rank=avengerRank;
    Name=avengerName;
    print("Rank of " + Name + " is " + rank.toString());
  }
}

void main() {
  Avengers marvel=new Avengers(1,"Captain Marvel");	
  Avengers thor=new Avengers(2,"Almighty Thor");
  Avengers hulk=new Avengers(3,"The Hulk");
}

Output :

Rank of Captain Marvel is 1
Rank of Almighty Thor is 2
Rank of The Hulk is 3

In above example, there are 3 objects Captain Marvel, Thor and Hulk of a particular class Avengers. Marvel, Thor and Hulk will get their separate copy of instance variables (i.e., Name and Rank) generated at the time of object creation. It is not required to create or declare properties for each object of class.

The default values for uninitialized variables of any data type in dart is null. Because everything else in dart is an object.

What is Reference Variable?

The reference variable reference to or point to the memory storage allocated for particular object created.

In simple language, reference variable is the alias or identifier for the declared objects.

For ex :

class Test{
}
void main(){
int x;	// x point to some random location like 0x02304 for object of type(class) int variable declared.

String y;	// y point to some random location like 0x089540 for object of type(class) String variable declared.

Test T1=new Test();	// test points to some random like 0x02560 for  object of type(class) Test declared.
}

In above example, x, y and T1 are different variables pointing to their respective objects stored in the memory.

They are just references of the objects to easily access them.

At a time, a reference variable can refer or point to the single object of the class. But, multiple reference variable can refer or point to same object.

For ex :

class Books{
}

void main(){
/* New Object of Class Book is created and referenced by the Reference variable B1.*/
	Book B1=new Book();	

/* Reference Variable B2 is created and ultimately refers to the same object referred by B1.*/
	Book B2=B1;	

/* New Object of Class Book is created and referenced by the Reference variable B3. */
	Book B3=new Book();	

/* Reference Variable B3 is created and ultimately refers to the same object referred by B2. */
	B3=B2;
}

In above example, the first statement will create a new object and will get some random storage location in memory. Let say, 0x0001 which is referenced by Reference variable B1.

The second statement will now have another reference variable B2 which will refer to the same object which is referenced by Reference variable B1 i.e., location 0x0001.

The third statement will create a new object and will get some random storage location in memory. Let say, 0x0003 which is referenced by Reference variable B3.

In 4th Statement reference variable B3 will now refer to the same object which is referenced by Reference variable B2 i.e., location 0x0001.

So now we have 2 Objects of class Book and 3 Reference Variables B1, B2 and B3 all pointing to the first object only. While, second object is not referenced by any reference variable.​

So this is the brief explanatory section for instance variable and reference variable.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Constructors

Dart constructor is an interesting topic which is used to initialise the objects of the class.

What is Constructor?

Basically, constructors are the special type of methods with the same name as the class but with no return type.

Constructors are used to initialise the data members(properties and behaviours) of an object at the time of object creation.

Syntax

// ConstuctorName must be same as the class name
ConstuctorName(){               
}

Types of Constructors

There are three types of constructors available in dart language.

  • Default Constructor
  • Parameterised Constructor
  • Named Constructor

Default Constructor

Constructor with no arguments is known as Default Constructor.

Each class can have only one Default Constructor.

If user don’t create the Default Constructor for particular class then compiler creates a Default (No-argument) Constructor for the class.

For ex :

class Television
{
  Television()
  {
     print("Television On!");
  }
}

void main()
{
/* new Keyword is not necessary with Dart 2 Release.*/
/* Round braces after Class Name  (i.e., Television) will Initialise the object and
 Call the Default Constructor whether you have created it or not.*/

  Television T1 = new Television();
}

Output :

Television On!

Parameterised Constructor

Constructors with one or more parameters (arguments) are known as parameterised constructor.

In dart, class can have only one parameterised constructor. But, can have more than one named constructor.

Syntax :

constructorName(parameterList);

For ex :

class Television
{
    Television(int a, int b)
    {
       print("Sum of 2 Numbers is " +(a+b).toString());
    }
}
void main()
{
  Television T1=new Television(5,4);
}

Output :

Sum of 2 Numbers is 9.

Named Constructor

In dart, class can’t have multiple constructors. A class can have either 1 default constructor or 1 parameterised constructor. To fulfil your multiple constructor requirement dart has a concept called Named Constructor.

Named Constructors are defined as ClassName following with “.” following VariableConstructorName.

Syntax :

ClassName.ConstructorName(parameterList){
}

For ex :

class Television
{
    Television(int a, int b)
    {
        print("Sum is : ${a+b}");
    }
    Television.Channel(String a, String b)
    {
        print("Channel 1 is " + a +" And Channel 2 is "+b);
    }
    /* Named Constructors can be defined as a private constructor by starting the constructor name with _ */
    Television._Channel(String a, String b,int c)
    {
        print("Channel 1 is " + a +" And Channel 2 is "+ b + " And Channel Rank is " + c.toString());
    }
}

void main()
{
    Television T1 = new Television(5, 4);
    Television T2 = new Television.Channel("Movie TV", "Sports TV");
    Television T3 = new Television._Channel("Movie TV", "Sports TV", 5);
}

Output :

Sum is : 9
Channel 1 is Movie TV And Channel 2 is Sports TV
Channel 1 is Movie TV And Channel 2 is Sports TV And Channel Rank is 5

In this way, constructors are useful to initialise the class members or initialise the resources which you want at the time of object creation.

It would be better to understand another topic “This Keyword” at this Moment to better enhance the use of constructors.

This Keyword

This keyword is used to refer the current instance(Object) or methods of the class.

General purpose of this keyword is to differentiate the parameters passes in method and instance variables if they have same name.

For ex :

class Actors
{
    String Name;
    int Age;
    Actors(String Name, int Age)
    {
        Name = Name;
        Age = Age;
    }
}
void main()
{
    Actors actor = new Actors("Tom Cruise", 40);
    print(actor.Name);
    print(actor.Age);
}

Output :

null
null

In above case, Name and Age will generate ambiguity for compiler. As instance variables and parameters passed in constructors have the same name.

So the values assigned in constructor to the Name and Age will not be assigned to the instance variable’s Age and Name.

In that case This keyword takes place to remove this kind of ambiguities introduced for compiler.

Let me explain this concept by correcting above example.

class Actors{
	String Name;
	int Age;
	Actors(String Name,int Age){
		this.Name=Name;
		this.Age=Age;
		// this.Test(); is same as the Test(); Function Call
		this.Test();
		
	}
	void Test(){
		print(“This Keyword”);
	}
}
void main(){
	Actors actor=new Actors("Tom Cruise",40);
  	print(actor.Name);
print(actor.Age);
}

Output :

Tom Cruise
40
This Keyword

Here you can see we have used this.Name and this.Age is used for referencing the instance variables of the class.

Here we also have made function call for Test() method in constructor using this keyword.

So “this keyword” is helpful to referencing the instance variables or methods of the class.

You can have command over the constructor and this keyword by practicing conventional programs.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.