2013-02-14 98 views
-2

我很努力地访问一个对象,它是来自另一个类的方法。 我写了一些代码来说明我的问题Java:在B类中创建的类A中创建的访问对象

注意:下面的代码不是可编译或可运行的,只是为了解释我的问题。

class MainClass { 
    public static void(String[] args) { 
     Run r = new Run(); 
    } 
} 

class Run { 

    Run() { 
     Brand cola = new Brand("Coca Cola"); 
     Brand pepsi = new Brand("Pepsi"); 

     // Creates the container object "con1" and adds brands to container. 
     Container con1 = new Container(); 
     con1.addToList(cola); 
     con1.addToList(pepsi); 
    } 

} 

class Brand { 
// In this class I have a method which needs to accsess the con1 object 
containing all the brands and I need to access the method 

    public void brandMethod() { 
     if(con1.methodExample) {  **// Error here. Can't find "con1".** 
      System.out.println("Method example returned true."); 
     } 
    } 

} 

class Container { 
    // This class is a container-list containing all brands brands 

    public boolean methodExample(){ 
    } 
} 

我很努力地从Brand类中访问“con1”对象。 我怎样才能访问“con1”?

+2

我搜索了你的确切问题标题,发现这个 - http://stackoverflow.com/questions/10570393/access-object-created-in-one-class-into-another你至少应该这样做在发布到SO之前进行大量研究。 – djechlin 2013-02-14 16:35:13

+0

问题不是如何访问对象,而是如何访问它的权利? – 2013-02-14 16:36:30

+0

另请参见[在另一个类中创建的访问对象](http://stackoverflow.com/questions/10570393/access-object-created-in-one-class-into-another/14885596#14885596) – 2013-02-14 23:01:10

回答

1

我会打电话给Brand

brand.addTo(collection); 

例如

public class Brand { 
    private Container container; 
    public void addTo(Container c) { 
     c.addToList(this); 
     container = c; 
    } 
} 

该品牌可以添加自己,并保存对该集合的引用。这确实意味着品牌有一个单一的收集参考,我不确定这真的是你想要的。

一个稍微好一点的解决方案是在构建Brand时提供容器,然后Brand然后仅将其自身添加到集合中,并从一开始就引用该集合。

+0

谢谢你的你的回复。那是一个好主意。创建一个新的品牌,并从Run类发送该集合。然后用它的藏品打电话给品牌。虽然我不知道该怎么写。你能帮我吗? – user1991083 2013-02-14 17:01:23

+0

参见上面的其他建议 – 2013-02-14 17:26:47

0

您必须使用对某个对象的引用,并对其进行初始化。

Container con1 = new Container(); <-- the inicialization by creating a new object. 

      ^
       | 
       | 
     the reference/variable 

UPDATE来回答COMMENT:错误行之前 你将不得不通过实例;通常作为该方法的一个参数。我担心你对Java基础知识的研究太少,这个问题有很多错误。

搜索以下概念:

  • 变量及其范围。
  • 局部变量vs实例变量vs静态变量。
  • 方法参数。
+0

但是通过添加Container con1 = new Container(),我丢失了存储在原始con1容器中的数据。我需要访问con1与存储的品牌。 – user1991083 2013-02-14 16:52:13