Classes
Classes are a template for creating objects.
defining classes are straight forward, you can define a new class like
ክፍል የዋጋ_አወጣጥ {
// class body
}A class ማስጀመሪያ method is a special function that's used to initialize objects when they are created. It allows you to set up the initial state or attributes of an object. there can only be one initializer with a name ማስጀመሪያ in a class.
ክፍል የዋጋ_አወጣጥ {
ማስጀመሪያ(ብር, ምንዛሪ) {}
// class body
}To reference the current object you can use the ይህ keyword.
ክፍል የዋጋ_አወጣጥ {
ማስጀመሪያ(ብር, ምንዛሪ) {
ይህ.ብር = ብር;
ይህ.ምንዛሪ = ምንዛሪ;
}
// class body
}here i am initializing ብር and ምንዛሪ attributes to the current object.
defining a class method is straight forward, you just define the method name and an opening bracket followed by optional arguments and a function body.
ክፍል የዋጋ_አወጣጥ {
ማስጀመሪያ(ብር, ምንዛሪ) {
ይህ.ብር = ብር;
ይህ.ምንዛሪ = ምንዛሪ;
}
ዋጋውን_አውጣ() {
አውጣ ይህ.ብር + " " + ይህ.ምንዛሪ;
}
}
መለያ ዋጋ = የዋጋ_አወጣጥ(100, "Dollar");
ዋጋ.ዋጋውን_አውጣ(); // prints 100 DollarTo create a class inheritance, use < keyword between the class that is being created and the the class that the new class inherits from.
A class created with a class inheritance inherits all the methods from another class.
ክፍል ምንዛሪ {
ማስጀመሪያ(የምንዛሪ_አይነት) {
ይህ.የምንዛሪ_አይነት = የምንዛሪ_አይነት;
ከሆነ (የምንዛሪ_አይነት == "Dollar") {
ይህ.ኮድ = "$"
} ካልሆነ {
ይህ.ኮድ = የምንዛሪ_አይነት
}
}
}
ክፍል የዋጋ_አወጣጥ < ምንዛሪ {
ማስጀመሪያ(ብር, ምንዛሪ) {
ታላቅ(ምንዛሪ);
ይህ.ብር = ብር;
}
ዋጋውን_አውጣ() {
አውጣ ይህ.ብር + " " + ይህ.የምንዛሪ_አይነት + " (" + ይህ.ኮድ + ")";
}
}
መለያ ዋጋ = የዋጋ_አወጣጥ(100, "Dollar");
ዋጋ.ዋጋውን_አውጣ(); // prints 100 Dollar ($)when i first initialize the class, i call the parent class with ታላቅ to initialize it, ታላቅ is equivalent to super in other languages.