Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Make inner classes be able to modify outer class

Let's say I have two classes:

public class OuterClass {
    String string = "helloworld";

    public class InnerClass {

        public void main(String[] args) {
            string = "lol";
            System.out.println(string);
        }
    }

    public void changeString() {
        InnerClass c = new InnerClass();
        c.changeString();
        System.out.println(string);
    }
}

The output will be:

lol
helloworld

Is there a way for the inner class to be able to modify the variables of the outer class? Thanks for all the help in advance.

like image 289
SalmonKiller Avatar asked Dec 29 '14 02:12

SalmonKiller


3 Answers

Because the variable string is static you can now access it from any class inside the class the variable is defined in i.e.InnerClass and therefore you can change the variable's value from InnerClass and also OuterClass. So the code will be:

public class OuterClass {
    public static String string = "helloworld";

    public class InnerClass {
        string = "lol";
    }

    public static void main(String[] args) {
        System.out.println(string);
    }
}

Hope this helps.

like image 83
Daniel Lewis Avatar answered Nov 15 '22 00:11

Daniel Lewis


Pass a reference to the outer class to the inner class in the constructor

public class InnerClass {

    private OuterClass parent;

    public InnerClass(OuterClass parent)
    {
       this.parent = parent;
    }

    public void changeString() 
    {
        parent.string = "lol";
        System.out.println(string);
    }
}

then inside of the class would instantiate using new InnerClass(this).

like image 27
konkked Avatar answered Nov 14 '22 22:11

konkked


I have made a change in the code where the inner class accesses outer class' object and modifies it.

public class OuterClass
{
    String string = "helloworld";

    public class InnerClass
    {
        public void changeString()
        {
            string = "lol";
        }
    }
    public static void main(String[] args)
    {
        OuterClass outerClass = new OuterClass();
        System.out.println(outerClass.string);
        outerClass.new InnerClass().changeString();
        System.out.println(outerClass.string);
    }
}

It's output is:

helloworld
lol
like image 28
Vishal Bansod Avatar answered Nov 14 '22 22:11

Vishal Bansod