将布尔方法从一个 class 传递给另一个
Passing boolean method from one class to another
我有 2 个 java 文件,名为 CastlingCheck.java 和 Board.java。 CastlingCheck.java 包含一个布尔方法 (testCastling),我想在 Board.java.
中调用该方法
CastlingCheck.java:
package chess;
public class CastlingCheck extends Board{
public boolean testCastling(int oldX, int oldY, int newX, int newY) {
int deltax = newX - oldX;
if (1st condition) {
**code here**
return true;
}
if (2nd condition) {
**code here**
return true;
}
if (3rd condition) {
**code here**
return true;
}
if (4thnd condition) {
**code here**
return true;
}
return false;
}
}
Board.java:
package chess;
...code...
public boolean testCastling(int oldx, int oldy, int newx, int newy) {
return true;
}
...code...
我做的对吗?
在 OO 编程中,您的目标是模仿真实世界。
所以首先,问问自己这个问题:CastlingCheck 是一个棋盘吗?
答案是:不,不是。所以 CastlingCheck 不是董事会。
在OO中,这种问题叫做继承,用extends关键字编程。
因此,CastlingCheck 不应扩展 Board。
现在要解决您的问题,请创建一个 CastlingCheck 实例 class 并调用该方法。
所以在董事会中 class:
CastlingCheck cc = new CastlingCheck();
boolean b = cc.testCastling(...);
但是你最好遵循一些设计原则,比如著名的 MVC。互联网上有很多这方面的信息。
我有 2 个 java 文件,名为 CastlingCheck.java 和 Board.java。 CastlingCheck.java 包含一个布尔方法 (testCastling),我想在 Board.java.
中调用该方法CastlingCheck.java:
package chess;
public class CastlingCheck extends Board{
public boolean testCastling(int oldX, int oldY, int newX, int newY) {
int deltax = newX - oldX;
if (1st condition) {
**code here**
return true;
}
if (2nd condition) {
**code here**
return true;
}
if (3rd condition) {
**code here**
return true;
}
if (4thnd condition) {
**code here**
return true;
}
return false;
}
}
Board.java:
package chess;
...code...
public boolean testCastling(int oldx, int oldy, int newx, int newy) {
return true;
}
...code...
我做的对吗?
在 OO 编程中,您的目标是模仿真实世界。
所以首先,问问自己这个问题:CastlingCheck 是一个棋盘吗?
答案是:不,不是。所以 CastlingCheck 不是董事会。
在OO中,这种问题叫做继承,用extends关键字编程。
因此,CastlingCheck 不应扩展 Board。
现在要解决您的问题,请创建一个 CastlingCheck 实例 class 并调用该方法。
所以在董事会中 class:
CastlingCheck cc = new CastlingCheck();
boolean b = cc.testCastling(...);
但是你最好遵循一些设计原则,比如著名的 MVC。互联网上有很多这方面的信息。