[英]my toString function is called without calling it
I'm very new to Java and I am making this program which randomly puts robots in a predefined arena. 我是Java的新手,我正在制作此程序,该程序将机器人随机放置在预定义的舞台上。
I was testing my addRobot method in the main when this happened 发生这种情况时,我正在主要测试我的addRobot方法
Here's the code of my 2 classes: 这是我的两个类的代码:
import java.util.Scanner;
import java.util.Random;
public class RobotArena {
private int xmax,ymax;
Robot ro;
RobotArena roaa;
public static Robot rrr[];
RobotArena (int xs, int ys, Random r){
xmax = xs;
ymax = ys;
ro = new Robot(r.nextInt(xmax), r.nextInt(ymax), this);
}
public void addRobot () {
Scanner add = new Scanner(System.in);
System.out.print("How many robots would you like to add?");
int numberofRobots = add.nextInt();
rrr = new Robot[numberofRobots];
add.close();
for(int c=0 ;c < numberofRobots ; c++)
{
Random addro2 = new Random();
int Xcoordinate = addro2.nextInt(xmax);
int Ycoordinate = addro2.nextInt(ymax);
rrr[c]= new Robot(Xcoordinate,Ycoordinate, null);
System.out.println( rrr[c]);
}
}
import java.util.Random;
public class Robot {
private int x, y, dx, dy, ID;
private static int RobotID;
private RobotArena roA;
Robot(){
this(0,0, null);
}
Robot(int sx, int sy, RobotArena ra){
x = sx;
y = sy;
dx = 1;
dy = 1;
roA = ra;
ID = RobotID;
RobotID++;
}
public String toString() {
return "Robot ID = " + ID +", robot is at " + x + ", " + y;
}
public boolean isHere(int ix, int iy) {
if (ix == x && iy == y) {
return true;
}
else
{
return false;
}
}
public static void main(String[] args) {
RobotArena rrr1;
Random addro = new Random();
rrr1 = new RobotArena(20, 5, addro);
rrr1.addRobot();
}
}
Even though I never call the toString function, which generates a string for every robot's ID and position in the Arena, 即使我从未调用过toString函数,该函数都会为竞技场中每个机器人的ID和位置生成一个字符串,
It is called indirectly . 它被间接称为。 You call System.out.println(rrr[c]);
您调用System.out.println(rrr[c]);
and the method is implemented such that it prints argument.toString()
of the given argument. 并实现该方法,以使其打印给定参数的argument.toString()
。
Let's take a look at a recent implemention ( 8u40-b25 ). 让我们看一下最近的实现 ( 8u40-b25 )。 System.out
points to an object of type PrintStream
, this is how its println
method is implemented: System.out
指向类型为PrintStream
的对象,这是其println
方法的实现方式:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
It calls String.valueOf(x)
( implementation ): 它调用String.valueOf(x)
( 实现 ):
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Which calls obj.toString()
on the argument. 在参数上调用obj.toString()
。
这是因为在Java中-如果您打印对象-toString方法将隐式调用
if you do : 如果您这样做:
System.out.println( rrr[c]);
then the println method is calling the toString for you internally... that is the real explanation of that beh. 那么println方法会在内部为您调用toString……这就是该行为的真正解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.