New a object ?

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I think we always new a class like below:ClassName1 OjbectName=new
ClassName1();But I find some example codes which new a class with different
classClassName1 OjbectName=new ClassName2();What is the purpose to do so?
 
The purpose is polymorphism. In OOP you can have a base class object
variable hold the addresses of derived class objects, and treat the object
polymorphically by calling virtual functions on the base class object
variable.
 
Hi ad,

Like Edward said a parent class or implemented interface can reference an
object.

class Parent
class Child : Parent

Parent p = new Child();

This is the same as
Child c = new Child();
Parent p = c;

p is just a reference to an object. All that is required of the p object
is that it can do everything
a Parent object can. This is very handy when you have methods that need
to handle different classes with a common parent or interface.

class FireMan : Human
class PoliceMan : Human

....
DoStuffToHuman(new FireMan())
....

void DoStuffToHuman(Human h)
{
}
 
Back
Top