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
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.
See more on this question at Stackoverflow