oop - Why can't we change access modifier while overriding methods in C#? -
in c#, can not alter access modifier while overriding method base of operations class. e.g.
class base of operations { **protected** string foo() { homecoming "base"; } } class derived : base of operations { **public** override string foo() { homecoming "derived"; } }
this not valid in c#, give compile time error.
i want know reason, why it's not allowed. there technical problem or can lead not consistent in terms of access restriction???
changing access modifier of method in derived type pointless that's why it's not allowed:
case 1: override more restrictive access
this case not allowed due next situation:
class base of operations { public virtual void a() {} } class derived: base of operations { protected override void a() }
now say:
list<base> list; list.add(new derived()); list[0].a() //runtime access exception
case 2: overriding less restrictive access modifier
what point? hide method , done. if calls through base of operations type not have access new method defined in derived type consistent how author of base of operations type wanted things have no "right" alter that. if want specifics of derived class phone call derived class, in case new
method works fine.
edit: expanding case 2
what trying in case 2, have means alter accessibility of method (virtual or not) if want alter accessibility.
consider next code:
public class base of operations { protected virtual string whoami() { homecoming "base"; } } public class derived : base of operations { public new virtual string whoami() { homecoming "derived"; } } public class anotherderived : derived { public override string whoami() { homecoming "anotherderived"; } }
with new
keyword have created new virtual method derived
class same name , signature. take note allowed declare new
method virtual
, class deriving derived
allowed override it.
what not allowed have following:
base of operations newbaseobject = new derived(); newbaseobject.whoami() //whoami not accessible.
but fact has nil beingness able override whoami()
or not. whatever case situation can never because base
not declare public
whoami()
.
so in theoretical c# derived.whoami()
override base.whoami()
there no practical benefits in doing because never able phone call virtual method base of operations class anyways, new
alternative meets requirements.
i hope makes clearer.
c# oop access-modifiers
No comments:
Post a Comment