如何在java中用布尔值编写构造函数?
我的代码如下所示:如何在java中用布尔值编写构造函数?,java,constructor,boolean,Java,Constructor,Boolean,我的代码如下所示: public class Cell { private boolean north; private boolean east; private boolean south; private boolean west; /** Construct a Cell, using the parameters given to initialize * the wall instance variables. *
public class Cell {
private boolean north;
private boolean east;
private boolean south;
private boolean west;
/** Construct a Cell, using the parameters given to initialize
* the wall instance variables.
*
* @param north
* @param south
* @param east
* @param west
*/
public Cell(boolean north, boolean east, boolean south, boolean west) {
?
}
如何使用布尔值编写构造函数?谢谢
boolean
没有什么不同,您可以像以下类型一样初始化它们:
必须使用关键字this
(即解决阴影)来引用字段变量,因为参数变量与字段具有相同的名称
public Cell(boolean north, boolean east, boolean south, boolean west) {
this.north = north;
this.east=east;
this.south=south;
this.west=west;
}
为什么您认为布尔值与其他任何东西都不同?您似乎在使用IDE,为什么不让IDE填充代码?您可能面临的“问题”是,您使用与成员变量相同的名称声明了参数。虽然您的成员变量将被隐藏。要访问它们,请使用
this.north
或重命名参数或成员。除了主要问题之外,为什么有四个布尔值来描述方向?在过去,你会有一些数值常量,比如public final int北=1,东=2,南=3,西=4
并让构造函数接受int方向
。现在您可以使用enum
来实现这一点。欢迎使用堆栈溢出!请仔细阅读,环顾四周,仔细阅读,特别是作业通常不是随意的;您的讲师、教程或课程将涵盖必要的主题,使您能够做到这一点。复习你的课程材料、课堂笔记等,并试一试。如果你遇到了一个特定的问题,彻底地研究它,如果你仍然困在那里,就发布你的代码和问题的描述。人们会乐意帮忙的。