Base Obj = new Derived()?

  • Thread starter Thread starter Akhil
  • Start date Start date
A

Akhil

Hi All,

Can u please explain this.

Base Obj = new Derived(); [Base being the base class and Derived being
the derived the class]

Can Obj access methods both of Base and Derived or what will be the
behaviour?
What will be the behaviour for Overridden Methods?

Cheers,
Akhil
 
Obj only can access methods of base(the Interface of Base ),but the behaviour
of method depend on the Derived(for the Overridden Methods or New
Methods,of couse the behaviour of the other method of Derived is same to
the Base)

hope it helps
 
Thanks, But Not Clear though.
--
Cheers,
Akhil

googou said:
Obj only can access methods of base(the Interface of Base ),but the behaviour
of method depend on the Derived(for the Overridden Methods or New
Methods,of couse the behaviour of the other method of Derived is same to
the Base)

hope it helps

Akhil said:
Hi All,

Can u please explain this.

Base Obj = new Derived(); [Base being the base class and Derived being
the derived the class]

Can Obj access methods both of Base and Derived or what will be the
behaviour?
What will be the behaviour for Overridden Methods?

Cheers,
Akhil
 
Since the reference type of obj is Base, you will be able to access only
those members of Base, and not that of Derived. Now, whose members get
invoked depends upon how the derived class has overriden the base members
etc. Unless the Derv have overridden the methods, Base's methods keep getting
called.
 
This example might help you understand:
class Class1
{
static void Main(string[] args)
{
Base obj = new Base();
obj.Show();

obj = new Derv();
obj.Show(); // This will invoke Derv's method, as it overrides Base's
method
obj.ShowWithNoVirtual(); // This will invoke Base's method, as the Base's
method is not virtual
//obj.DervMethod(); This won't work as obj refers to a Base type instance
}

}

public class Base
{
public void ShowWithNoVirtual()
{
Console.WriteLine("Base - no virtual");
}

public virtual void Show()
{
Console.WriteLine("Base");
}
}

public class Derv : Base
{
public void DervMethod()
{
}

public new void ShowWithNoVirtual()
{
Console.WriteLine("Derv - no virtual");
}

public override void Show()
{
Console.WriteLine("Derv");
}
}

Akhil said:
Thanks, But Not Clear though.
--
Cheers,
Akhil

googou said:
Obj only can access methods of base(the Interface of Base ),but the behaviour
of method depend on the Derived(for the Overridden Methods or New
Methods,of couse the behaviour of the other method of Derived is same to
the Base)

hope it helps

Akhil said:
Hi All,

Can u please explain this.

Base Obj = new Derived(); [Base being the base class and Derived being
the derived the class]

Can Obj access methods both of Base and Derived or what will be the
behaviour?
What will be the behaviour for Overridden Methods?

Cheers,
Akhil
 
Back
Top