Java Make inner classes able to modify the 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? Thank you for your help.

+5
source share
5 answers

Since the variable string is static , now you can access it from any class inside the class where the variable is defined, i.e. InnerClass , and so you can change the value of a variable from InnerClass , as well as OuterClass . Thus, 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.

+2
source

Pass the 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 an instance will be created inside the class using new InnerClass(this) .

+2
source

You will need to pass an instance of the outer class to the constructor of the inner class, and then assign it to a member variable, then you can refer to this member variable

+1
source

Your example does not compile, but you can fix it with something like

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

which displays (on request)

 lol lol 

Edit

Based on your comment below and using Java 8

 String string = "helloworld"; public class InnerClass { public void changeString() { string = "lol"; System.out.println(string); } } public static void main(String[] args) { OuterClass m = new OuterClass(); InnerClass c = m.new InnerClass(); c.changeString(); System.out.println(m.string); } 
+1
source

I made changes to the code in which the inner class accesses the object of the outer class 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); } } 

At the exit:

 helloworld lol 
+1
source

Source: https://habr.com/ru/post/1210021/


All Articles