NoviceToDotNet
NoviceToDotNet

Reputation: 10805

why a protectd method of a class can nor be accessed by creating its object in sub class?

i have a code like this, but giving error can not access protected member.

**Class A
{
protected void m1()
       {
        some code
       }
}
Class B:A
{
B b=new B();
b.m1();// Ok works fine
A a =new a();
a.m1();///   don't work, compile time error
A a2=new B();
a2.m1(); //compile time error, don't work
}**

just not getting reason behind this, Why so aberrant nature of the above code, why a method of a class using same class object not accessible out side. While i searched a bit for this but did not undersand, i found something that compiler nature come in picture, but i did not understand.

Upvotes: 0

Views: 75

Answers (2)

hallie
hallie

Reputation: 2845

As stated above, the protected method inside the class can only be accessed by the class that inherits the original container.In your case B is the sub class, a is your base. Inside your B class you are creating a new instance of A class ('a'), and this is now a different object (B class does not care about this new object A). This new object 'a' will not expose the protected method, so 'a.m1()' will throw a compile error.

Upvotes: 1

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

you can prefix your call by base keyword for calling base members. protected means that a member could be inherited by descendants and could be called but through the specified way.

calling a.m1() in your class hasn't any difference with calling it form an out of B code.

Upvotes: 1

Related Questions