如何编写包含布尔值的构造函数? [英] How to write a constructor that contains a boolean value?
问题描述
这是一个愚蠢的问题,但是自从我使用java以来已经有很长一段时间......我怎样才能用布尔值编写构造函数,或者我应该编写一个默认构造函数?我最近一直在使用C ++而且我已经忘记了很多java的语法。
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 constructor? I have been working with C++ most recently and I've forgotten a lot of syntax for java.
这是我到目前为止所做的:
This is what I have so far:
public class Creature {
protected int terrain;
public static final int DESERT = 0;
public static final int MOUNTAIN = 1;
public static final int FOREST = 2;
//symbols on cards
boolean flyingCreature = false;
boolean magicCreature = false;
boolean canCharge = false;
boolean rangedCombat false;
public int specialAbility = 0;
public Creature(int startTerrain, boolean flying, boolean magic, boolean charge, boolean ranged, int special){
?
}
}
当我做的时候我似乎找不到任何东西搜索...如何初始化构造函数中的每个值?或者我应该只是
I can't seem to find anything when I do a search... How do I initialize each value in my constructor? or should I just have
public Creature(){
startTerrain = DESERT;
flyingCreature = false;
magicCreature = false;
canCharge = false;
specialAbility = 0;
} ?
我还有几个继承自这个的类,所以我不确定这是否有所不同。
I also have several classes inheriting from this one, so I'm not sure if that makes a difference.
推荐答案
布尔参数与任何其他类型一样。
A boolean parameter is just like any other type.
所以,就像这样。
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.
因为你有继承这个的类,所以它们的构造函数必须调用 super( )
,它调用父类构造函数。如果你在没有任何参数的情况下调用它,将调用Creature的基础构造函数。
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.
这篇关于如何编写包含布尔值的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!