Interactions between Objects
Learn how objects work with each other.
We'll cover the following...
Before discussing data structures, we must know how objects work with one another and how different objects pass messages between themselves. We’ll also try to insert data into a linked list manually. This is a list of elements connected with a link.
We’ll use four easy-to-understand sample Dart programs to see how one object works with other objects. Let’s talk about the first program. Suppose we have a group of people, and each person acquires a mobile application that helps them to enter their tasks. They can categorize the tasks, and according to the necessity, they finish their tasks.
Code for multiple classes
To accomplish this task, we need to have two classes—Person
and the mobile application (AppToDo
) class. We need an application object inside the Person
class because one person object acquires one application object. The application object has a blueprint or class that defines what it can and can’t do.
Let’s code the two classes. Once a person acquires an application object, they can start doing everything defined in the mobile application class with that object.
//Dartvoid main(){var appOne= AppToDo("AppToDoOne");var appTwo= AppToDo("AppToDoTwo");var john= Person("John");var mac= Person("Mac");john.taskToDo= appOne;mac.taskToDo= appTwo;print("${john.name} gets ${john.taskToDo.name}.");print("${mac.name} gets ${mac.taskToDo.name}.");/*John gets AppToDo One.Mac gets AppToDo Two*/print("${john.name} is entering tasks.");john.taskToDo.task="Going to the market to get some vegetables";john.taskToDo.type="Marketing";john.taskToDo.enterTask();//we presume that every task is importantjohn.getTaskFinished(appOne);print("${mac.name} is entering tasks.");mac.taskToDo.task="Going out with friends";mac.taskToDo.type="Outing";mac.taskToDo.enterTask();//in some cases, the task may not be so importantappTwo.isImportant= false;mac.getTaskFinished(appTwo);}class AppToDo{String name;String task;String type;bool isImportant=true;AppToDo(Stringname){this.name = name;}void enterTask(){print("I want to finish this task - ${task}. It belongs to this type - ${type}.");}}class Person{String name;AppToDo taskToDo;Person(String name){this.name = name;}void getTaskFinished(AppToDo taskToDo){this.taskToDo = taskToDo;if(taskToDo.isImportant){print("This task - ${taskToDo.task} is important and needs to be finished.");} else {print("It can be avoided; it is not so important");}}}
Each person object is a separate entity, and each application object is a separate entity. However, all separate objects have some commonalities that are defined in the class.
We can expect the following output:
John gets null.
Mac gets
...