I'm trying to create a set of classes where a common ancestor is responsible for all the logic involved in setting various properties, and the descendants just change the access of properties depending on whether they are required in the particular descendant.
When I try to do it as shown below I get a compiler error: "cannot change access modifiers when overriding 'protected' inherited member"
Is there a way to achieve what I'm trying to do? Thanks
public class Parent
{
private int _propertyOne;
private int _propertyTwo;
protected virtual int PropertyOne
{
get { return _propertyOne; }
set { _propertyOne = value; }
}
protected virtual int PropertyTwo
{
get { return _propertyTwo; }
set { _propertyTwo = value; }
}
}
public class ChildOne : Parent
{
public override int PropertyOne // Compiler Error CS0507
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public override int PropertyTwo // Compiler Error CS0507
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
Changing the access modifier of a method in a derived type is pointless that's why it's not allowed: Case 1: Override with a more restrictive access This case is obviously not allowed due to the following situation:
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
In fact, PHP has three access modifiers: public, private, and protected. In this tutorial, you’ll focus on the public and private access modifiers. The public access modifier allows you to access properties and methods from both inside and outside of the class.
Example of protected access modifier In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
You can do this by using "new" instead of "override" to hide the parent's protected property as follows:
public class ChildOne : Parent
{
public new int PropertyOne // No Compiler Error
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public new int PropertyTwo
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With