Good day! I can not figure out how to use the protected method of another base class in my inheriting class.
For example, I have a class MyClass , I inherit a class YourClass with a method
protected void meth1 ()

I can not change anything in another class, getters and setters will not help, then how can I use this method, what methods are possible? Thank.

  • Describe in detail who inherits whom. And from what place do you want to get access to the protected method - jimpanzer
  • one
    Give the code. It is not clear where the problem is: protected methods from objects of the generated classes could always be used without problems. - VladD

2 answers 2

In this case, the simplest option is to create a public method in its class that will call the protected method from the ancestor.

    You can easily use methods marked as protected access modifier in the descendant classes. For this purpose, this access modifier was introduced, which is how it differs from private

    The protected keyword is a member access modifier. Access to a member with the protected modifier is possible inside the class and from the derived class instances.

    For example:

     public class YourClass { protected int YourMethod() { return 1; } } public class MyClass : YourClass { public MyClass () { var a = YourMethod(); // вернет 1 } } 

    Read more about protected here.

    • The question, as I understand it, is about using the protected method for a class derived from another class. As you correctly noted, the descendants will not have problems using this method. - Dmitry Lepeshkin
    • I read the question and comment a couple more times. I did not fully realize the whole point. But most likely the task will be reduced to obtaining the instans of the heir in the right place. - jimpanzer