0
    public class containerClass {

        private String checkAccess;
        public void checkAccessFunc(){ 

        }

        public class innerClass{

            public String InnerClassStr;
            public void InnerClassFunc(){ }

            //Inner class accessing outer class
            public containerClass c = new containerClass();
            c.checkAccess = 'Str';

        }

    }

The above piece of code is throwing me an error - Error: Compile Error: unexpected token: '=' at line 15 column 22

How else is it possible for inner class to access outer class and vice versa ?

Thanks.

  • @Ratan - Why for petes sake are you doing this. You just bumped many of the new questions off of the main page. There is no need to update year old question with trivial tag updates in bulk – Eric Jul 22 '16 at 7:25
  • @Eric is it? sorry I thought that need to clean up – Ratan Paul Jul 22 '16 at 7:34
  • 1
    @Ratan - Maybe this is a question for the meta group. But the edits did not improve the question or the answers so bringing them up to theta after being long buried thus bumping new question down or off the page may not be a good thing. – Eric Jul 22 '16 at 7:36
0

Here is how you can access the outer class variables.

public class containerClass {

        private String checkAccess;
        public void checkAccessFunc(){ 

        }

        public class innerClass{

            public String InnerClassStr;

            containerClass outercls;
            public innerClass (containerClass outercls) {
               this.outercls = outercls;
            }

            public void InnerClassFunc(){
                //Inner class accessing outer class
                outercls.checkAccess = 'Str';
            }

        }

    }
1

The error is actually saying that you can't have an assignment expression that does not follow a declaration on line 15. In other words:

public containerClass c = new containerClass();

Is a legal statement, because c is being defined in innerClass's scope. However, the next line:

c.checkAccess = 's';

Isn't valid here, only because you can't have a non-declaration assignment at this point in your code. You could, however, have done this:

public innerClass() {
    c = new containerClass();
    c.checkAccess = 's';
}

Inside a constructor or initializer block, or inside any normal function, you have access to any references of containerClass that is inside your instance, as well as all static variables and methods of containerClass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.