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.
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.
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With