如何从其他类访问某些变量?例如,我有2个文件:
Main.java
package keyboardgame;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends Applet implements KeyListener
{
private static final long serialVersionUID = 1L;
private static boolean keyboardRightPressed = false;
private static boolean keyboardLeftPressed = false;
private static boolean keyboardUpPressed = false;
private static boolean keyboardDownPressed = false;
int ballX = 20;
int ballY = 20;
int ballSpeed = 10;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboardRightPressed = true;
ballX = ballX + ballSpeed;
repaint();
}
if(keyCode == KeyEvent.VK_LEFT)
{
keyboardLeftPressed = true;
ballX = ballX - ballSpeed;
repaint();
}
if(keyCode == KeyEvent.VK_UP)
{
keyboardUpPressed = true;
ballY = ballY - ballSpeed;
repaint();
}
if(keyCode == KeyEvent.VK_DOWN)
{
keyboardDownPressed = true;
ballY = ballY + ballSpeed;
repaint();
}
}
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboardRightPressed = false;
repaint();
}
if(keyCode == KeyEvent.VK_LEFT)
{
keyboardLeftPressed = false;
repaint();
}
if(keyCode == KeyEvent.VK_UP)
{
keyboardUpPressed = false;
repaint();
}
if(keyCode == KeyEvent.VK_DOWN)
{
keyboardDownPressed = false;
repaint();
}
}
public void keyTyped(KeyEvent e) {
}
public void paint(Graphics g)
{
g.fillOval(ballX,ballY,20,20);
g.drawString("Right :"+keyboardRightPressed,0,10);
g.drawString("Left :"+keyboardLeftPressed,0,20);
g.drawString("Up :"+keyboardUpPressed,0,30);
g.drawString("Down :"+keyboardDownPressed,0,40);
}
}
KeyThread.java
package keyboardgame;
public class KeyThread implements Runnable
{
public KeyThread(String s,int speed)
{
name = s;
time = speed;
}
public void run()
{
try
{
if(keyboardRightPressed == true)
{
ballX = ballX + 10;
ballY = ballY + 10;
}
}
catch(Exception e)
{
}
}
}
我想要的是 KeyThread.java 能够修改/增加/访问 Main.java 中的值,尤其是
int ballX = 20;
int ballY = 20;
所以我可以从 Main.java 中调用我的帖子,如
Thread t5 = new Thread(new KeyThread("Moving Right", ballX = ballX + 1, 20));
t5.start();
我该怎么做? 为什么这么难呢?
答案 0 :(得分:2)
为了调用对象的非静态方法,您需要该类的实例。有关详细信息,请参阅Objects。
答案 1 :(得分:1)
如果您声明变量public
而不是private
,则可以将它们称为(例如)Main.ballX
,但这通常是一种不好的做法。我们将事物组织成课程以将各个事物分开;如果我们开始在类B中使用类A的成员,那么类B依赖于A,这可能使以后难以调试和维护。更好的方法是在Main(例如getBallX()
和setBallX(int x)
)中提供一个“getter”或“accessor”方法,它可以让拥有类(在本例中为Main)更好地控制其私有成员。 / p>
答案 2 :(得分:1)
此外,添加到其他答案,如果一个频繁的任务将要添加/减去该值似乎是一个方法,如adjustBallX(int x)可能是有价值的,所以你可以增加/减少每次都不调用get()和set()的值。