Java: Passing an instance of “this” during instantiation [closed]

馋奶兔 提交于 2019-12-11 02:57:00

问题


myClass1:

public class myClass1
{
    public myClass2 myclass2;

    public void createsecondclass (String[] args)
    {
        myclass2 = new myClass2(this);
        myclass2.dosomething();
    }

myClass2:

public class myClass2
{
    public myclass1;

    public myClass2(myClass1 myclass1)
    {
        this.myclass1 = myclass1;
    }

    public void dosomething()
    {
        myclass1.another_object_that_could_be_placed_here.dosomething();
    }
}

would this not make the code cleaner when trying to access a large amount of objects which all in one way or another are all instantiated under a single class? i ask because i am trying to learn libGDX and in the large assortment of class files that are made to handle each element of the game it just seems easier to pass my application listener down the line since the application listener contains the screen which contains the gameworld which contains the player and so on...

But the problem that i worry about is that by setting it to a variable in the object i am creating a myclass1 that contains a myclass2 that contains a myclass1 and so on. i worry that this might cause memory leaks and since my target is android, memory is a big concern.

if anyone has any thoughts on the subject, directly relevent or not i would appreciate the input. i am after all still learning.

thanks =)

来源:https://stackoverflow.com/questions/17494474/java-passing-an-instance-of-this-during-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!