Ask Your Question
3

What is the method to modify a variable in an inner class?

asked 2022-04-04 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-05-14 00:00:00 +0000

bukephalos gravatar image

To modify a variable in an inner class, you can either pass the instance of the outer class to the inner class and modify the variable using that instance, or declare the variable as "final" and modify it using a setter method within the outer class. Here is an example:

public class OuterClass {
    private int variable = 10;

    public class InnerClass {
        public void modifyVariable() {
            // method 1:
            OuterClass.this.variable = 20;

            // method 2:
            // declare the variable as final in the outer class
            // and create a setter method
            // OuterClass.this.setVariable(20);
        }
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-04 11:00:00 +0000

Seen: 11 times

Last updated: May 14 '22