Skip to content

Instantly share code, notes, and snippets.

@mhmadip
Created October 11, 2023 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhmadip/e62a4107fbe60e4e5f1bea4947be8624 to your computer and use it in GitHub Desktop.
Save mhmadip/e62a4107fbe60e4e5f1bea4947be8624 to your computer and use it in GitHub Desktop.
OOP Principles Example in Dart with Pokemon Context
// 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