0

How to use protected function of base class in derived class?

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    obj.Test(); // error thrown;
  }
}

When i tried to use the Test function of base class. It is throwing error..

Jagz W
  • 855
  • 3
  • 12
  • 28

6 Answers6

2

You can call the Test() method directly without having to create a new object of the base type:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    Test();  // Calls the test method in the base implementation of the CURRENT B object
  }
}
2

I think one could do it through a protected static method in the base class, without losing the encapsulation.

public class A
{
  protected void Test() { /* ... */ }

  protected static void Test(A obj)
  {
    obj.Test();
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    A.Test(obj);
  }
}

Effectively A.Test() can be called only from derived classes and their siblings.

A snippet for testing: http://volatileread.com/utilitylibrary/snippetcompiler?id=37293

Albus Dumbledore
  • 12,368
  • 23
  • 64
  • 105
1

That's because 'A's Test() is protected, which means, B sees it as private.

The fact that B inherits from A, and that A contains Test which is protected, doesn't mean that other objects can access Test, even though they inherit from that class.

Although:

Since B inherits from A, B contains the private method Test(). so, B can access it's own Test function, but that doesn't mean B can access As Test function.

So:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test(); // Will work!
  }
}
Shai
  • 25,159
  • 9
  • 44
  • 67
1

Test is protected within an instance of object A.

Just call

this.Test()

No need to create the object A within B.

Totero
  • 2,524
  • 20
  • 34
1

Seems you misunderstood the word "protected". Have a look at msdn: http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.71).aspx

Your example needs to be like this:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test();
  }
}
walther
  • 13,466
  • 5
  • 41
  • 67
0

Protected methods are only available to derived types. In other words you are trying to access the method publicly when you create an instance of A.

devdigital
  • 34,151
  • 9
  • 98
  • 120