Declare An Object In Dart
Code snippet for how to Declare An Object In Dart with sample and detail explanation
Object-oriented programming (OOP) represents a fundamental concept in various programming languages, including Dart. This article aims to exhibit how to declare an object in Dart effectively and intending to provide a comprehensive understanding.
Code Snippet for Object Declaration
In Dart, before we can create objects, we need to define classes. A class is a blueprint for an object. Once we have a class, we can create an instance of the class, which is an object. Here is a simple example of declaring an Object in Dart:
class Student {
var studID;
var studName;
showStudInfo(){
print(studID);
print(studName);
}
}
void main() {
var student1 = new Student(); // Creating Instance of student
student1.studID = 1001; // Setting up studID
student1.studName = "Amy"; // Setting up studName
student1.showStudInfo();
}
Code Explanation for Object Declaration
Let’s break down the previous Dart code snippet to understand more:
-
We first declare a class named
Student
with properties:studID
andstudName
. This class also has ashowStudInfo
function that prints out the student’s ID and name. -
In the
main()
function, we create an instance ofStudent
class calledstudent1
. Thenew
keyword is being used before theStudent
constructor to create a new object from the class. -
After creating the
student1
object, we assign values tostudID
andstudName
properties using the dot.
operator. It is worth noting that property values are not fixed and can be changed by the object’s user. -
Finally, we call the function
showStudInfo()
for the student1 object. Again, the dot.
operator is used to call this function. This function will print the values ofstudID
andstudName
.
In conclusion, an object in Dart is declared by first defining the class and then creating an instance of the class. The instance, in this case, is student1
, and the class is Student
. Through the instance, we can access and manipulate the properties and functions defined in that class.