-8

Is is possible to access a protected variable from a private class. Is Yes what will happen and how it works?

private class classname{
    protected int variable_name = 5;
    private void method_name(){

         response.write(variable_name);

    }
}

this was asked in my interview

shiva sankar
  • 61
  • 1
  • 9

1 Answers1

2

Yes, it's possible and it means exactly the same as normal:

public class Container
{
    private class Foo
    {
        protected int field;

        private class FurtherNested
        {
            // Valid: a nested class has access to all the members
            // of its containing class
            void CheckAccess(Foo foo)
            {
                int x = foo.field; 
            }
        }
    }

    private class Bar : Foo
    {
        void CheckAccess(Foo foo)
        {
            // Invalid - access to a protected member
            // must be through a reference of the accessing
            // type (or one derived from it). See
            // https://msdn.microsoft.com/en-us/library/bcd5672a.aspx
            int x = foo.field; 
        }

        void CheckAccess(Bar bar)
        {
            // Valid
            int x = bar.field;
        }
    }

    private class Baz
    {
        void CheckAccess(Foo foo)
        {
            // Invalid: this code isn't even in a class derived
            // from Foo
            int x = foo.field;
        }
    }
}

That said, it's relatively unusual to have any type deriving from a private (and therefore nested) type.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for explanation Jon, I was not knowing about the fact "Invalid - access to a protected member must be through a reference of the accessing type (or one derived from it)." – Jenish Rabadiya Feb 26 '15 at 13:51
  • @JenishRabadiya: That's just a normal part of the meaning of the protected modifier. Will add an MSDN reference to the code, as a comment. – Jon Skeet Feb 26 '15 at 13:52