简体   繁体   中英

Using the constructor of the base class when creating new object of derived class?

    Public class A
    {
    ...
    }
    Public class B:A
    {
    ...
    }
    Public class Prog
    {
    public static void Main()
    {
         A myA = new B();
    }
}

If myA is an instance of A class, why I use B constructor, and how it differ from this:

A myA = new A();

also this code may be closer to this issue: 在此处输入图片说明

I know this may be very basic question, but I'm really confused.

You don't have to use the B constructor, only if you want an instance of B that inherits A .

You can also setup B so that is calls the constructor of A for you, eg:

public class A
{
    public A()
    {
    }
}

public class B : A
{
    public B() : base()
    {
    }
}

It all entirely depends on the implementation of your A and B classes and what you want to use them for.

Edit:

In light of your image, the reason you are calling like Vehicle c = new Car() is because the object you are actually creating is a Car but you still want or need to use aspects of the base class. Having this base class means you can have common properties between implementing classes.

For example:

public class Vehicle
{
    public Vehicle()
    {
    }

    public int NumberOfWheels { get; set; }
}

public class Car : Vehicle
{
    public Car() : base()
    {
        NumberOfWheels = 4;
    }
}

public class Motorbike : Vehicle
{
    public Motorbike() : base()
    {
        NumberOfWheels = 2;
    }
}

This case allows you to only define NumberOfWheels once and just set the value appropriately for the implementation you are writing. You can do the same thing with methods using virtual methods.

A myA = new B();

This is creating an object of type B . It is not creating an object of type A . However , you are casting the object to A . Casting in layterms essentially means you are saying 'View this object as if it were an A . Ignore the fact that it may be a B . Only show me methods and properties which were defined in the class A ).

Note that you can re-cast it back to B , which does not change the object whatsoever:

B myB = (B)myA;

The difference between this:

A myA = new A();

and this:

A myA = new B();

Is that the first statement is creating a physical object of type A . Any overrides or new method/properties/fields defined in B will not be created . The second statement will create a physical object of type B , but to view it (even temporarily) as an A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM