Categories
Dart

Dart Typedef

In dart, Typedef is a keyword used to declare alias or reference to the function in the program. With the help of this alias or reference we can call different functions having same signature(i.e., having same number of parameters with same data types). For typedef, return type does not considered as part of the function signature.

In short, typedef is used to call(refer) the different functions having the same signature assigned to typedef for smoother function manipulation.

Syntax :

// Here, parameterList stands for different types of parameters required in function.
typedef variableName(parameterList);

For ex :

// here,  SportLegends is the typedef variable which can be assigned to the different functions having same signature as declared with typedef.
typedef SportLegends(String Player1,String Player2);

// Tennis function have same signature(i.e., both String type parameters) as typedef SportLegends().
Tennis(String Player1, String Player2){
  print("$Player1 and $Player2 are two great players of tennis.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Cricket(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Cricket.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Football(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Football.");
}

void main(){
  SportLegends legends;
  // assigning typedef to reference the Tennis function having the same signature as typedef  SportLegends.
  legends=Tennis;
  legends("Roger Federer","Rafael Nadal");
  legends=Cricket;
  legends("Sachin Tendulkar","AB De Villiars");
  legends=Football;
  legends("Cristiano Ronaldo","Lionel Messi");
}

Output :

Roger Federer and Rafael Nadal are two great players of tennis.
Sachin Tendulkar and AB De Villiars are two great players of Cricket.
Cristiano Ronaldo and Lionel Messi are two great players of Football.

Hence, typedef becomes really useful to point-out different functions having same signature with single variable to reduce boiler-plate coding.

It can be useful to learn typedef as it makes your work very handy to map different functions with single variable as per your requirements.

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 Advanced Functions

Dart functions don’t need classes for writing different functions. Which means dart treats functions as first class objects.

Dart supports advance level functions like lambda functions.

Lambda functions are a concise and efficient mechanism to represent functions with lesser code and better performance.

Syntax of Lamda :

returnType functionName(arguments) => expressions;

For ex :

game(){

/* here return type will be decided at runtime based on the value return from the function. In this case we are returning 100 so, the return type of function game is int type.*/

return 100;

}

// above code can be written as,
game()=>100;

I think this is amazing because Lambda function removes boiler plate code from your programming and optimize your work efficiency.

Lambda function with parameters

parameters passed in lambda functions do not need to specify the data type. The data type of the parameter will be interpreted based on the value passed.

For ex :

game(gameName,rank)=>"rank $rank game of the world is $gameName";
void main(){
  print(game("Minecraft",1));
}

in above example, we didn’t declare the data type for arguments. As It is optional to pass parameters for the lambda functions in dart.

In above example, gameName variable will be assigned to String data type as the value passed to parameter is “Minecraft” which is of String type.

This way lambda functions are useful for reducing the code as well as provding simplified syntax structure.

Optional parameters

Yes, dart supports optional parameters in the functions.

Optional parameters are the parameters which are not necessary to pass in the function call.

Optional parameters can have default values (if any values are not passed for optional parameters the optional parameter will have that default value we have provide in the function definition signature).

Optional parameters can be declared only after the required parameters.

There are two types of optional parameters

  1. Positional parameters
  2. Named parameters

Positional Parameters

Positional parameters are the type of optional parameters which are included inside square brackets – [ ] .

In any function, if you have declared more than one positional parameters then you have to pass them in the same order as you have defined in the function signature.

For ex :

void main(){
		// order of passing parameters is important in function call with positional parameters.
		watchMovies("An Action Movie","Star wars", 1999);
		watchMovies("An Action Movie","Terminator");
}

// watchMovies() has default int positional parameter year with value 1984. Any function call to watchMovies function without positional parameter year will be assigned default value 1984.
watchMovies(String category, [String movie, int year = 1984]){
  print(movie + " was $category released in "+ year.toString());
}

Output :

Star wars was An Action Movie released in 1999
Terminator was An Action Movie released in 1984

Named Parameters

Named parameters are the type of optional parameters which are included inside curly brackets – { } .

Named parameters are the parameters which can be passed in function call with the name we have used for that particular parameter in the function signature.

To pass named parameters in function call, you must have to use parameter name defined in the function signature.

Function calling with named parameter will be look like below,

// Here, parameterName is the name defined in function. ParameterValue will be assigned to that parameterName.
function call(parameterName : parameterValue);

For ex :

void main(){
  // Here, year and series are named parameters which are defined in the method signature of watchSeries().
 watchSeries("A Drama Series",year: 2011, series: "Game of Thrones");
}

// Any function call to watchSeries() function without named parameter year will be assigned default value 3000.
watchSeries(String category, {series, year=3000}){
  print(series + " was $category released in "+ year.toString());
}

Output :

Game of Thrones was A Drama Series released in 2011
The Walking Dead was A Drama Series released in 2010

In named parameters, you can change the order of passing the optional parameters in function calling as we did in above example.

These are some of the advance approaches available in dart functions to make your programs smoother and easy to code.

Also, dart programs can run with only functions without use of class-object structure.

This shows that how much vital role functions play in dart language. So, mastering functions in dart will help your large projects more redable.

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 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.