简体   繁体   English

Java-如何在多个类中使用同一对象

[英]Java - how to use the same object in many classes

I'm new here so please forgive possible mistakes :) 我是新来的,所以请您原谅可能的错误:)

I'm writing a game as a final project for my coding classes. 我正在编写一个游戏,作为我的编码课程的最终项目。 And...I'm really stuck. 而且...我真的很困。 I want to create one object of certain class BUT later on I need to pass there different data from different other classes so I can save all data at the end of using a program. 我想稍后创建一个特定类的对象,我需要从那里传递来自其他不同类的不同数据,以便在使用程序结束时保存所有数据。

For example I create an object in MainFrame and get a name of a user from there. 例如,我在MainFrame中创建一个对象,并从那里获取用户名。 Then I go to NextFrame and get age of a user etc etc. 然后我转到NextFrame并获取用户年龄等等。

I'd appreciate the answers in as simple english as possible, I'm not fluent :) I'm using netbeans btw. 我希望以尽可能简单的英语来回答问题,我不太流利:)我正在使用netbeans btw。 Thanks a lot ! 非常感谢 !

Simply try the Singleton Design Pattern. 只需尝试Singleton设计模式。

Simple Example for that: 一个简单的例子:

class SingletonClass {
    private static SingletonClass instance = null;
    private String customAttribute;

    public SingletonClass() {
        //default constructor stuff here
    }

    //important singleton function
    public static SingletonClass getInstance() {
        if(instance == null)
            instance = new SingletonClass();
        return instance;
    }

    // getter and setter
}

now, in your frame or any other class you just do the following: 现在,在您的框架或任何其他班级中,您只需执行以下操作:

SingletonClass myObject = SingletonClass.getInstance();

when this function is called for the first time, a new Object is created. 首次调用此函数时,将创建一个新的对象。 Later, it returns the first created. 稍后,它返回创建的第一个。 With the help of the Singleton Pattern you can easily save data in one object across multiple classes. 借助Singleton Pattern,您可以轻松地将数据保存在多个类中的一个对象中。

for more information about Singleton: http://en.wikipedia.org/wiki/Singleton_pattern 有关Singleton的更多信息: http : //en.wikipedia.org/wiki/Singleton_pattern

hope this helps. 希望这可以帮助。

just pass the object to the class you want to, and use it accordingly in a method that you want to ! 只需将对象传递给所需的类,然后在所需的方法中相应地使用它即可! Here is an example with two classes: 这是带有两个类的示例:

class oneClass {
   void oneMethod() {
      Class1 myClass1 = new Class1();
      Class2 myClass2 = Class2 Class2();
      myClass2.setMyClass1(myClass1);
   }
}

class Class2 {
   Class1 myClass1;
   //...
   void setMyClass1(Class1 myClass1) {
     this.myClass1 = myClass1;
   }
   //...
   void doSomething() {
      // do something with instance variable myClass1
   } 
}

In your case Class1 can be MainFrame and Class2 can be NextFrame or however you want to call them... 在您的情况下, Class1可以是MainFrameClass2可以是NextFrame或者您想调用它们...

As you can see from my code, you pass the class myClass1 to myClass2 using the following line of code : myClass2.setMyClass1(myClass1); 从我的代码可以看到,您可以使用以下代码myClass2.setMyClass1(myClass1);myClass1传递给myClass2myClass2.setMyClass1(myClass1); and then you can work in this object any way you want 然后您可以按任何方式在此对象中工作

Just send the object of your MainFrame class using a method to wherever you want. 只需使用一种方法将MainFrame类的对象发送到所需的任何位置即可。 The object will contains all data from whenever you change it from different method. 只要您使用其他方法更改对象,该对象将包含所有数据。

If you need a single object MainFrame all over the class then you may consider of using singleton pattern for creating the object. 如果整个类都需要单个对象MainFrame ,则可以考虑使用单例模式创建对象。

to save things to a file(or stream) you can use interface serializable: 要将内容保存到文件(或流)中,可以使用可序列化的接口:

import java.io.Serializable;
import java.util.ArrayList;

public class Test implements Serializable {

public ArrayList<Object> urDiferentKindOfThings = new ArrayList<Object>();

public boolean add(Object o) {
    if (o != null) {
        urDiferentKindOfThings.add(o);
        return true;
    }
    return false;
}
}

Now, just add anything (Object!) that you want to save, then at the end of your game just save the object of type TEST that should contain all your stuff (you may need to read about serializable as it make life easy) 现在,只需添加要保存的任何内容(对象!),然后在游戏结束时保存应该包含所有内容的TEST类型的对象(您可能需要阅读有关可序列化的内容,因为它使生活变得容易)

Good Look 好看

You pass class instances into a managing class 您将类实例传递给管理类

public class Game {

    private MainFrame mainframe = null;
    private NextFrame nextframe = null;


    public Game(){
        this.mainFrame = new MainFrame();
        this.nextFrame =  new NextFrame();  
    }

    public Game(MainFrame mainFrame, NextFrame nextFrame){
        this.mainframe = mainFrame;
        this.nextframe = nextFrame;
    }    

    public String getName(){
        return mainFrame.getName();
    }

    public int getAge(){
        return nextFrame.getAge();
    }

}


public class MainFrame {
    private String name = "John"

    public String getName(){
        return name;
    }
}

public class NextFrame{
        private int age = 25;

        public int getAge(){
            return age;
        }
}
class a{
  function dosomething(){
     //code goes here
   }
}

class b{
    a firstobject=new a();
    c secondobject=new c(a objtopass);  //passing object of a to c
    function donext(){
        //next code
    }
}

class c{
a receivedobj=null;
public c(a objtoreceive){
    //constructor
    receivedobj=objtoreceive;
}
 function doAdd(){
   //function code
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM