Java: Passing an instance of “this” during instant

2019-07-23 00:17发布

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 =)

0条回答
登录 后发表回答