method hiding – c# ^ java

C# hiding rules Based on [[c# primer]] P148.

— virtual methods —
Rule – for virtual methods, there’s no hiding — base version is completely “replaced”. If Account and CheckingAccount both define
v1(), and we have a CheckingAccount instance, then we can’t invoke the base v1(), even if we upcast.

Virtual method rule is fairly simple compared to non-virtual methods —

— non-static non-virtual —
Rule – If Account and CheckingAccount both define non-virtual, non-static method m1() with identical signature, then hiding occurs.
We are strongly advised (not required) to mark the hiding explicit using “new”.

Hiding affects only static, compile-time method binding. Suppose we have a CheckingAccount instance myAccount. Both m1() versions
are available at runtime, unlike the virtual method v1().

myAccount.m1();// is the derived version

( (Account)myAccount ).m1(); // is the base version. Static binding

Inside CheckingAccount source code, we can also use base.m1(). This is same as java.

— static methods —
Rule – java method hiding applies to static method only. Simple and clean. How about c#? I guess same.

I feel c++ hiding rules are less comparable. I feel c# borrowed more from Java than from c++.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s