tags:

views:

75

answers:

4

I'm trying to establish a default value for inherited fields from superclasses.

So, my class hierarchy is thus:

Character -> Enemy -> Boss
                \
                  -> Hero

Each Character has a public static char avatar to represent him on an ASCII playing field.

How do I set a default value for the avatar of each class inherited from Character?

Thank you!

+2  A: 

You could set it in the constructor. For example:

public class Hero extends Character {
    public Hero() {
        avatar = 'H';
    }
}

But, for this to work, avatar property must not be static (othervise all your avatars will be the same, as set in the constructor of the last instantiated class). Your Character class should probably look something like this (provided that you want default avatar for classes that don't set theirs in constructor):

public class Character {
    public char avatar;
    public Character() {
        avatar = 'A';
    }
}
Domchi
A: 

A good idea is to provide methods in the base class to be implemented such as 'createWeapon()', and then use these methods to set final fields in the constructor. The methods will return the default object unless overridden.

Edit: don't make these fields static. There's no point. You can return static versions of these objects as defaults if you only want to maintain single default instances. But your example seems more simple using a char, for instance. In this case, there wouldn't be much benefit. Just return the character.

Chris Dennett
+2  A: 

avatar can not be a static field because if you change it in any of the sub classes, it will get changed for all sub classes. You can implement it like this.

public class Character{
     public char avatar = '';
     public Character(char avatar){
          this.avatar = avatar;
     }
}

public class Enemy extends Character{
     public Enemy(char avatar){
          super(avatar);
     }
}

public class Boss extends Enemy{
     public Boss(char avatar){
          super(avatar);
     }
}

public class Hero extends Character{
     public Hero(char avatar){
          super(avatar);
     }
}

With this approach, you will have the avatar for each class for which you are creating the object. In the above example, if you declare avatar as static, for each object ecreation, it will change the value of the field for all the classes.

RaviG
Perhaps avatar should be final? :-)
Steven Schlansker
No it can not be. If you declare it as final, you can not assign values in that.
RaviG
A: 
  • don't use static
  • set the default value with private char avatar = 'A'
  • provide getAvatar() and setAvatar(char c) methods, which modify the avatar
  • in the constructor of subclasses call the setter with the desired values
Bozho