Shelby
Shelby

Reputation: 3

Only changing value when inheriting

I'm currently working on a very simple Pokémon application in C#. I was uncertain on how to set up the relationship between the Pokémon and their fighting type but I just ended up doing the following:

 abstract class Pokemon
{
    private int number;
    private string name;
    protected string weakness;
    protected string strength;

    public Pokemon(int number, string name)
    {
        this.number = number;
        this.name = name;
        weakness = "none";
        strength = "none";
    }
}

I then made seperate classes that inherit Pokemon only to change the specific weakness and strength of the type.

class Fire : Pokemon
{
    public Fire(int number, string name) : base(number, name)
    {
        weakness = "Water";
        strength = "Grass";
    }
}

Is it bad etiquette to create subclasses with the sole purpose of simply changing some of the initial values of the parent?

From here on, I just intend on doing the following when "creating" Pokémon for the application

        pokemon = new Pokemon[6];
        pokemon[0] = new Grass(001, "Bulbasaur");
        pokemon[1] = new Grass(002, "Ivysaur");
        pokemon[2] = new Grass(003, "Venusaur");
        pokemon[3] = new Fire(004, "Charmander");
        pokemon[4] = new Fire(005, "Charmeleon");
        pokemon[5] = new Fire(006, "Charizard");

Any and all advice on how to improve the application or how to use inheritance properly is much appreciated :)

Upvotes: 0

Views: 69

Answers (1)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5147

The inheritance looks OK but you may do some improvements. First, you don't need to define protected fields for weakness and strength, use protected properties instead. Second, using string type for weakness/strength doesn't seem to be the best choice. I would go with an Enum type.

enum PokemonComponent {
   Water,
   Grass
}

abstract class Pokemon
{
    private int number;
    private string name;
    protected Pokemon(int number, string name)
    {
        this.number = number;
        this.name = name;
    }
    protected abstract PokemonComponent Weakness {
      get;
    }
    protected abstract PokemonComponent Strength {
       get;
    }
}

class Fire : Pokemon
{    
    public Fire(int number, string name) : base(number, name)
    {
    }
    protected override PokemonComponent Weakness {
      get {
         return PokemonComponent.Water;
      }
    }
    protected override PokemonComponent Strength {
      get {
         return PokemonComponent.Grass;
      }
    }
}

Upvotes: 1

Related Questions