开发者

Is it possible to establish default values for inherited fields in subclasses?

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

So, my class hierarchy is thus:

Character -> Enemy -> Boss

                \

     &nb开发者_开发知识库sp;            -> 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!


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';
    }
}


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.


  • 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜