Class activation

I am new to C #. I have one confusion.

There are two classes A and B.

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            A objA = new A();

            A objB = new B();
        }
    }

    class A
    {
        public void MethodA()
        {
            Console.WriteLine("method of A class");
        }
    }

    class B : A
    {
        public void MethodB()
        {
            Console.WriteLine("method of B class");
        }
    }
}

Now the confusion that I have is that the meaning is:

A objB = new B();

I saw and instantiated a class such as thi:

A objB = new A();

Can someone tell me why we used:

A objB = new B();

Thanks in advance.

+3
source share
5 answers

Because the class is Binherited from A, instances Bare also instances A, and polymorphism ensures that any instance Bcan be assigned A.

The purpose of your code only demonstrates this concept.

+4
source

, B, A. , . :

A objB = new B();
B realObjB = (B)objB;

, , A, , , B.

:

class Program
{
    static void Main(string[] args)
    {
        Truck truck = new Truck();

        TellMeHowManyWheelsThisHas(truck);
    }

    private static void TellMeHowManyWheelsThisHas(Vehicle vehicle)
    {
        Console.WriteLine("This vehicle has {0} wheels", vehicle.HowManyWheelsDoIHave());
    }
}

abstract class Vehicle
{
    public abstract int HowManyWheelsDoIHave();
}

class Car : Vehicle
{
    public override int HowManyWheelsDoIHave()
    {
        return 4;
    }
}

class Truck : Vehicle
{
    public override int HowManyWheelsDoIHave()
    {
        return 8;
    }
}
+4

.

i.e B A. hense A objB ( ) B. objB A.

google for Upcasting/DownCasting

+1

, , objB A, , B, .

.

- : ( )

class Vehicle { public void Drive(); }
class Boat : Vehicle { public void LowerAnchor(); }
class Car : Vehicle { public void SoundHorn(); }

Vehicle boat = new Boat();
boat.Drive();
Vehicle car = new Car();
car.Drive();

, boat car boat car , , , . Drive() , , .

+1
using System;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            A objA = new A();
            A objB = new B();
            Console.ReadLine(); // only used to keep the output on-screen
        }
    }

    class A
    {
        public A()
        {
            Console.WriteLine("method of A class");
        }
    }

    class B : A
    {
        public B()
        {
            Console.WriteLine("method of B class");
        }
    }
}

, , . , , , . :

method of A class
method of A class
method of B class

, , , , .

0
source

Source: https://habr.com/ru/post/1771282/


All Articles