Polymorphism and the Virtual Method

Suppose the class Vehiclecontains a method virtualwith a name CalculateMaxSpeed. Suppose both methods MotorVehicleand Automobile overridethis method. Which class defines the method that is called when the second statement is executed in the following code?

Vehicle(grandparent of Automobile)> MotorVehicle(parent Auatomobile)>Automobile

MotorVehicle car = new Automobile();
car.CalculateMaxSpeed();

Well, from my point of view, it should be Automobile#CalculateMaxSpeed, but I'm afraid it may be MotorVehicle#CalculateMaxSpeedbecasue MotorVehiclecontains an instance Automobile. Please check with someone.

+4
source share
2 answers

Your understanding is correct. Automobile#CalculateMaxSpeedwill be called. This is called Runtime Polymorphism.

MotorVehicle, derviced, Automobile. , , .

, .

+2

, , , :

public class A 
{
     public virtual string Text { get; set; }
}

public class B : A
{
     // "new" keyword is identifier reusing. You're
     // defining a new member which uses Text again and
     // hides "Text" to references typed as B
     new public string Text { get; set; }
}

public class X : A
{
     public override string Text { get; set; }
}


B someB = new B();
someB.Text = "hello world";

// Now try to access Text property... what happened?
// Yes, Text property is null, because you're reusing the 
// identifier in B instead of overriding it
A someBUpcastedToA = someB;
string text = someBUpcastedToA.Text;

X someX = new X();
someX.Text = "goodbye";

// Now if you access someXUpcastedToA.Text
// property it will give you the "goodbye" string
// because you're overriding Text in X instead of
// reusing the identifier
A someXUpcastedToA = someX;

, , , - , .

, :

// someX reference provides access to all X members
X someX = new X();

// This is upcasting. Now it still the X instance but
// with access to less members. 
A a = someX;

(.. public string Text) . , , , , . , , .

0

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


All Articles