在多个方法中运行类的单个实例

时间:2016-04-27 02:46:30

标签: java

我关心的课程是:

public class Gscore
    private score;

    public void setscore(float a)
    {
        float Score=a;
    }

    public getscore()
    {
        return Score;
    }

在两个单独的java文件中,我想在一个文件中设置一个分数并访问另一个java文件中的设置值。这两个文件的片段如下:

档案1

Gscore scoregen= new Gscore();
scoregen.setscore(playerscore);
new file2;

文件2

Gscore scoregen= new Gscore();
System.out.print(scoregen.getresponse());

但是,结果总是为null,我做错了如何让文件2显示​​我在文件1中设置的值。

2 个答案:

答案 0 :(得分:1)

您的主要问题是您没有在这两种方法中使用相同的类实例。您正在两次实例化GScore类。仅具有相同的引用变量名称并不等同于相同的实例。

实例化实例后,将相同的对象引用传递给第二个方法。您应该能够获得非NULL的结果。

答案 1 :(得分:1)

首发

Public void setscore(int a)
{
Float Score=a;  // this is a problem as this is local scope
}

其次,要使用相同的Object,您应该只将其实例化一次,然后将其传递给其他类。

另一种可能性是使用Singleton类http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm