c# - who is who or creating objects from extended class -
try understand power of oop
create 3 classes
class { public string foo() { return "a"; } } class b:a { public string foo1() { return "a"; } } class program { static void main(string[] args) { a = new b(); //can use method b b = new b(); //both aa = new a(); //just string result = b.foo(); string n = ((a)b).foo().tostring(); } }
currently try understand difference between a = new b(); , a = new a(); - try use - can use same method classes - see pic
also try understand difference beetwen
b b = new b(); ((a)b).foo();
and
a = new b(); b.foo();
and
a =(А) new b(); , a = new a();
also try find tutorial explanation of main principles of oop, still have question. understanding
the simplest difference is:
a = new b(); b b = (b) a; // works!
a = new a(); b b = (b) a; // compiler error
even if assign b
instance a
-typed variable it's still instance of b
class, can cast b
.
but that's simple example. real differences pop out when class have virtual
methods
class { public virtual void foo() { console.writeline("a : foo();"); } }
that override
n
class b : { public override void foo() { console.writeline("b : foo();"); } }
and/or hidden:
class c : { public new void foo() { console.writeline("c : foo();"); } }
within derived classes. class declarations you'll following results:
{ a = new a(); b b = new b(); c c = new c(); a.foo(); // prints : foo(); b.foo(); // prints b : foo(); c.foo(); // prints c : foo(); } { a = new a(); // prints : foo(); b = new b(); // prints b : foo(); c = new c(); // prints : foo(); a.foo(); b.foo(); c.foo(); }
that's more interesting, isn't it? should read more overriding , hiding methods , class inheritance in general..
Comments
Post a Comment