如何将调用方法的对象作为参数传递给 Java 中的方法?

How to pass an object that is calling a method as an argument to the method in Java?

我在一个名为 Ship 的 class 中有一个名为 PositionSetter 的方法。它需要一个 Board 对象作为参数。每个 Board 对象都应该调用 PositionSetter 方法,并将其自身作为参数传递。我该怎么做呢? 代码:

public void PositionSetter(Board BattleshipBoard, Ship ship)
{
  //do stuff with BattleshipBoard and ship  
}

同样,调用上述方法的对象是一个需要将自身作为参数传递的 Board 对象。欢迎使用我的方法的替代方法。

试试下面的东西。

Main.java

public class Main
{
public static void main(String[] args) {
     Ship ship=new Ship();
     ship.PositionSetter(ship);  // call method inside Ship class
 }
}

Ship.java

public void PositionSetter(Board BattleshipBoard, Ship ship)
{
   //do stuff with BattleshipBoard and ship  
}

完全看不懂你的意思

猜猜看。

首先, 可以写一个接口,比如:

public interface ObjInter {
}

那么,其他调用该方法的对象必须实现该接口,如:

public class Board implements ObjInter {
    ...
}

最后,你的方法可以这样写:

public void PositionSetter(Board BattleshipBoard, ObjInter obj) {
    //do stuff with BattleshipBoard and ship  
}

以上是否满足你的问题?

如果您的 Board Class 中有一个 ship 对象 'shipOne', 您可以从 Board class 调用其 PositionSetter 方法,如下所示:

shipOne.PositionSetter(this,shipOne);

这回答了你的问题。
不过我有以下建议:
1.I 认为董事会 class 有责任在其 position.I 中设置船舶 不知道为什么在船舶 class.
中有 PositionSetter 方法

2.Also 我不明白需要 ship argument.If 它是正在传递的调用该方法的同一艘船,那么你不必传递它。 无论如何它都可以在方法中作为 'this' 访问。

3.Method 名称应遵循驼峰命名 convention.Please 参考这里: http://www.oracle.com/technetwork/java/codeconventions-135099.html
祝你的 BattleShip 游戏好运!