Declaring class in Dart:
- A Class is a blueprint for creating objects.
Syntax:
class class_name{
//Body of class
}
Class is the keyword use to initialize the class.
class_name
is the name of the class.
Declaring objects in Dart:
Objects are the instance of the class and they are declared by using new keyword followed by the class name.
Syntax:
var object_name = new class_name([ arguments ]);
new
is the keyword use to declare the instance of the class.object_name
is the name of the object and its naming is similar to the variable name in dart.class_name
is the name of the class whose instance variable is been created.arguments
are the input which are needed to be pass if we are willing to call a constructor.After the object is created, there will be need to access the fields which we will create. We use the
dot(.) operator
for that purpose.Syntax:
// For accessing the property object_name.property_name; // For accessing the method object_name.method_name();
Reference Variable:
A reference variable is simply a variable that holds a reference (or memory address) to an object in memory rather that directly containing the object's data.
Imagine you have a house (an object) that you want to refer to in a conversation. Instead of carrying the entire house around with you, you just hold a key (reference) to the house.
House (Object): The actual thing you're referring to, like the data in your program (e.g., a person, a car, etc.).
Key (Reference Variable): A variable that holds a reference to where the object (the house) is located in memory, like a memory address.
So, when you create an object in Dart, you're essentially creating a house, and the variable you assign it to holds the key to that house's location. If you want to talk about the house again, you just use the key (reference) instead of carrying the entire house (object) around.
you can create class objects and reference variables as follows:
dartCopy code// Define a class
class Person {
String name;
int age;
// Constructor
Person(this.name, this.age);
// Method
void greet() {
print('Hello, my name is $name and I am $age years old.');
}
}
void main() {
// Create an instance of the Person class
var person1 = Person('Jinali', 21);
// Reference variable pointing to the instance
var person2 = person1;
// Changing a property of person2 will reflect in person1 as well
person2.name = 'Reet';
// Accessing properties and calling methods using reference variables
print(person1.name); // Output: Reet
person1.greet(); // Output: Hello, my name is Reet and I am 21 years old.
}