Saturday, 15 August 2015

override - Can a static method be overriden in C#? -



override - Can a static method be overriden in C#? -

i told static methods implicitly final, hence can't overriden. true?

1) can give improve illustration of overriding static method?

2) , if static methods class methods, real utilize of having them?

(1) static methods cannot overridden, can hidden using 'new' keyword. overriding methods means reference base of operations type , want phone call derived method. since static's part of type , aren't subject vtable lookups doesn't create sense.

e.g. statics cannot do:

public class foo { public virtual void bar() { ... } } public class bar : foo { public override void bar() { ... } } // use: foo foo = new bar(); // create instance foo.bar(); // calls bar::bar

because statics don't work on instances, specify foo.bar or bar.bar explicitly. overriding has no meaning here (try expressing in code...).

(2) there different usages static methods. example, it's beingness used in singleton pattern single instance of type. illustration 'static void main', main access point in program.

basically utilize them whenever don't want or cannot create object instance before using it. example, when static method creates object.

[update]

a simple hiding example:

public class statictest { public static void foo() { console.writeline("foo 1"); } public static void bar() { console.writeline("bar 1"); } } public class statictest2 : statictest { public new static void foo() { console.writeline("foo 2"); } public static void some() { foo(); bar(); } // print foo 2, bar 1 } public class teststatic { static void main(string[] args) { statictest2.foo(); statictest2.some(); statictest.foo(); console.readline(); } }

note if create classes static, cannot this. static classes have derive object.

the main difference between , inheritance compiler can determine @ compile-time method phone call when using static. if have instances of objects, need @ runtime (which called vtable lookup).

c# override static-methods final

No comments:

Post a Comment