gpt4 book ai didi

java - 构造函数调用是否必须是构造函数中的第一条语句?

转载 作者:行者123 更新时间:2023-12-01 17:22:52 27 4
gpt4 key购买 nike

我有一个 cShape 类来处理图形图像。它在其构造函数中占据起始位置。我希望起始位置是随机的,所以我有以下代码

cBalloon(Context InContext, int w, int h) {
// set up random postion
Random randomGenerator = new Random();

int sx=randomGenerator.nextInt(w);
int sy=randomGenerator.nextInt(h);

super( InContext, sx, sy, 0,0, 50,50, "balloon", 50,50,0);
}

我收到一条错误消息“构造函数类必须位于构造函数的第一个”有办法做到这一点吗?

最佳答案

super(...) 必须是构造函数中的第一条语句。

但是,有一个解决方法:创建一个静态方法

private static int getRandomtInt(int x) {
Random randomGenerator = new Random();
return randomGenerator.nextInt(x);
}

并在 super 构造函数中调用它:

cBalloon(Context InContext, int w, int h) {
super( InContext, getRandomInt(w), getRandomInt(h), 0,0, 50,50, "balloon", 50,50,0);
}

关于java - 构造函数调用是否必须是构造函数中的第一条语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com