Hello there! In today's lesson, we're delving deeper into Dart classes, concentrating on attributes and methods. Attributes define properties, while methods define actions. We'll be exploring these concepts using a Dog
class as an example. Upon completing this lesson, you will have attained proficiency in the use of attributes and methods within Dart classes.
From an object-oriented perspective, attributes can be considered as properties. For instance, in a Dog
class, the attributes might include name: "Fido"
, breed: "Poodle"
, color: "White"
. These attributes provide a detailed characterization of a dog's attributes.
Attributes can be introduced to a class in Dart as follows. In this case, we're setting the name
, breed
, and color
for the Dog
class:
Dart1class Dog { 2 var name = 'Fido'; 3 var breed = 'Poodle'; 4 var color = 'White'; 5}
To create an instance, the following pattern is used:
Dart1var fido = Dog(); 2 3print(fido.name); // Prints: Fido 4print(fido.breed); // Prints: Poodle 5print(fido.color); // Prints: White
In this instance, Fido
is an object of the Dog
class.
Simplified, methods can be defined as actions that instances of a class can undertake. For the Dog
class, behaviors might include bark()
, eat()
, and sleep()
. Such methods are defined as functions within the class itself.
When we introduce methods to the Dog
class, we enable it to perform actions like barking, eating, and sleeping:
Dart1class Dog { 2 var name = 'Fido'; 3 var breed = 'Poodle'; 4 var color = 'White'; 5 6 void bark() { 7 print('Woof Woof!'); 8 } 9 10 void eat(String food) { 11 print('$name is eating $food.'); 12 } 13 14 void sleep() { 15 print('Zzz...'); 16 } 17}
In this manner, the bark
, eat
, and sleep
methods define the behavior of a Dog
object. Now, an instance of Dog
can bark, eat, and even sleep.
Let's create an object from the Dog
class and call its methods:
Dart1var fido = Dog(); 2 3print(fido.name); // Prints: Fido 4print(fido.breed); // Prints: Poodle 5print(fido.color); // Prints: White 6 7fido.bark(); // Prints: Woof Woof! 8fido.eat("bone"); // Prints: Fido is eating bone. 9fido.sleep(); // Prints: Zzz...
With attributes and methods, our Dog
class truly comes to life!
That's it for this lesson! With attributes and methods, you can render Dart classes more interactive. We demonstrated the application of attributes and methods using the Dog
class. Your next step is to tackle exercises designed for you to practice and reinforce these concepts. Happy Dart coding!