0

I want to access private member of a class by anonymous class created in a different class. I am new to java, kindly please explain this and tell what i am doing wrong.

class movie{
    private String moviename="bahubali";
    void display(){
        System.out.println(moviename);
   }
}

public class InnerClass{ //main class

    public static void main(String[] args) {
        movie anonymous=new movie() {
            void display() {
                System.out.println(moviename+" in anonymous class");
            }
        };
    
        anonymous.display();
    }
}
4
  • 1
    movie is not an outer class. It's rather a separate class altogether. Commented Jul 30, 2021 at 12:26
  • 1
    anonymous class or inner class? Commented Jul 30, 2021 at 12:30
  • @RinkalRohara so can you tell where this anonymous class is created by the compiler? is it in Main class or in the movie class? Commented Jul 31, 2021 at 5:46
  • @VeKe anonymous is also a inner class of non static type Commented Jul 31, 2021 at 5:47

1 Answer 1

2

Your anonymous class inherits from the class movie (you should make it Movie instead btw. to comply with Java standards).

Inheriting classes are granted access to protected members, not to private members.

So the fix in this case should be changing

private String moviename="bahubali";

to

protected String moviename="bahubali";

.

Sign up to request clarification or add additional context in comments.

1 Comment

i m just practicing concepts so forget about java naming standards. i was just checking that anonymous can access private members of the outer class, so i just figured out that we can do this in enclosing class(in my case -can access the private member of main class which is InnerClass).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.