How to write a constructor that contains a boolean value?

前端 未结 3 1719
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 05:24

This is a dumb question but it\'s been a long time since I\'ve worked with java... How can I write my constructor with Boolean values or should I just write a default construct

相关标签:
3条回答
  • 2021-01-27 05:58

    You probably appropriately chose the primitive type boolean in your example but since you mentioned "Boolean" with a capital "B", there is a difference. Boolean variables are nullable unlike the primitive "boolean" with a lower case "b". If you had used Booleans, you can simply initialize those like

    Boolean boolVar = Boolean.TRUE; //or Boolean.FALSE
    

    And they might later require null checks depending on the situation.

    0 讨论(0)
  • 2021-01-27 06:00

    A boolean parameter is just like any other type.

    So, it would be like this.

    public Creature(int startTerrain, boolean flying, boolean magic, boolean charge, boolean ranged, int special){
            terrain = startTerrain;
            flyingCreature = flying;
            magicCreature = magic;
            canCharge = charge;
            rangedCombat = ranged;
            specialAbility = special;
    }  
    

    If these parameters are going to be always the same on the beggining, then you can set them on a default constructor, as you said.

    Since, you have classes inheriting this one, their constructor will have to call super(), which calls the parent class constructor. If you call it without any parameters, the base constructor of Creature will be called.

    0 讨论(0)
  • 2021-01-27 06:07

    If you use the constructor which has parameters, it goes like this

    this.flyingCreature = flying;
    this.magicCreature = magic;
    

    and so on.

    If you use the constructor without any parameters (the default constructor), then you need to set the class fields to some constants (like you did). So you do e.g.

    this.flyingCreature = false;
    this.magicCreature = false;
    

    and so on.

    The use of this. is not mandatory unless you have a parameter with the same name in which case you should use this. otherwise your initialization code will have no effect on the class field.

    0 讨论(0)
提交回复
热议问题