Created with <3 with dartpad.dev.
Last active
October 11, 2023 11:27
-
-
Save mhmadip/b1f19b106dcffe79b8e3f019459362aa to your computer and use it in GitHub Desktop.
obsidian-eucalyptus-4097
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OOP Principles Example in Dart with Pokemon Context | |
// 1. Classes and Objects | |
abstract class Pokemon { | |
String name; | |
int level; | |
Pokemon(this.name, this.level); | |
// 3. Abstraction (Abstract method representing a move) | |
void performMove(); | |
void attack() { | |
print("$name attacks!"); | |
performMove(); | |
} | |
} | |
// 2. Inheritance | |
class ElectricPokemon extends Pokemon { | |
ElectricPokemon(String name, int level) : super(name, level); | |
@override | |
void performMove() { | |
print("$name uses an electric attack!"); | |
} | |
} | |
class FirePokemon extends Pokemon { | |
FirePokemon(String name, int level) : super(name, level); | |
@override | |
void performMove() { | |
print("$name breathes fire!"); | |
} | |
} | |
// 4. Polymorphism | |
void pokemonInfo(Pokemon pokemon) { | |
pokemon.attack(); | |
} | |
// 5. Encapsulation | |
class PokemonTrainer { | |
List<Pokemon> party = []; | |
void addPokemon(Pokemon pokemon) { | |
party.add(pokemon); | |
} | |
void pokemonBattles() { | |
for (var pokemon in party) { | |
pokemon.attack(); | |
} | |
} | |
} | |
void main() { | |
// Creating Pokemon | |
var pikachu = ElectricPokemon("Pikachu", 15); | |
var charizard = FirePokemon("Charizard", 30); | |
// Polymorphism | |
pokemonInfo(pikachu); // Outputs: Pikachu attacks! Pikachu uses an electric attack! | |
pokemonInfo(charizard); // Outputs: Charizard attacks! Charizard breathes fire! | |
// Encapsulation | |
var ash = PokemonTrainer(); | |
ash.addPokemon(pikachu); | |
ash.addPokemon(charizard); | |
ash.pokemonBattles(); | |
// Outputs: | |
// Pikachu attacks! Pikachu uses an electric attack! | |
// Charizard attacks! Charizard breathes fire! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment