表达动态多态性



根据用户输入的动物危险等级,calculate_insurance方法将选择正确的案例并运行计算以确定动物保险的成本。危险等级设置在父类中保险计算是在具有动态多态性的2个子类中通过覆盖父类来完成的。解决这个问题的最佳方法是什么?将非常感谢您对代码的解释

基本类-

public abstract class Animal
{
protected int danger_rating = 0;
//get danger rating from user (1-5)
while (true)
{
Console.WriteLine("What is the animals danger rating? nSelect a number between 1 - 5: "); //Prompt user to type in animals danger rating
string input = Console.ReadLine(); //reads string input 
if (int.TryParse(input, out danger_rating)) //convert user string input to int danger_rating
{
if (danger_rating == 1) //loop until danger_rating is between 1 and 5
{
break;
}
else if (danger_rating == 2)
{
break;
}
else if (danger_rating == 3)
{
break;
}
else if (danger_rating == 4)
{
break;
}
else if (danger_rating == 5)
{
break;
}
else
{
Console.WriteLine("Invalid Number. nNumber must be between 1 - 5");
}
}
else
{
Console.WriteLine("This is not a number");
}
public virtual double calculate_insurance(int danger_rating)
{
return 0;
} 
}

哺乳动物类-

public class Mammal : Animal //Derived class
{
public virtual double calculate_insurance(int danger_rating)
{
int ins_base = 5000; //base for mammals

double Insurance; //this will contain the output
//Select case based on danger rating 1 - 5
switch (danger_rating)
{
case 1:
Insurance = (ins_base * 10) * 0.02;
break;
case 2:
Insurance = (ins_base * 20) * 0.05;
break;
case 3:
Insurance = (ins_base * 30) * 0.05;
break;
case 4:
Insurance = (ins_base * 40) * 0.05;
break;
case 5:
Insurance = (ins_base * 50) * 0.10;
break;
default:
Console.WriteLine("Invalid danger rating");
break;
} //end of switch
return base.calculate_insurance(danger_rating);
}
}

爬行动物类-

public class Reptile : Animal //Derived class
{
public virtual double calculate_insurance(int danger_rating)
{
int ins_base = 1000; //base for reptiles

double Insurance; //this will contain the output
//Select case based on danger rating 1 - 5
switch (danger_rating)
{
case 1:
Insurance = (ins_base * 10) * 0.02;
break;
case 2:
Insurance = (ins_base * 20) * 0.05;
break;
case 3:
Insurance = (ins_base * 30) * 0.05;
break;
case 4:
Insurance = (ins_base * 40) * 0.05;
break;
case 5:
Insurance = (ins_base * 50) * 0.10;
break;
default:
Console.WriteLine("Invalid danger rating");
break;
} //end of switch
return base.calculate_insurance(danger_rating);
}
}

我真的不确定"求解";,除了在方法级别浮动循环的while基类中的语法错误和一些不确定因素之外,在这些不确定因素中,您为派生类型计算了一些保险值,但随后返回了基类型的保险计算值(即0(。

Mammal和Reptile中的calculate_insurance方法应声明为override基方法,并且应以return Insurance结束(注意;它应被称为insurance;我们在PascalCase中不命名局部变量(,而不返回调用基的结果。。

如果你在问如何使用你创造的东西。这种性质的多态性背后的想法是,你可以有一个基本类型的变量,而不知道或不关心它里面存储的实际类型,因为你只使用基本类型声称存在的功能

Animal a = new Mammal();
a.calculate_insurance(1);  //returns 1000, the rating for a Mammal of type 1
Animal b = new Reptile();
b.calculate_insurance(1);  //returns 200, the rating for a Reptile of type 1

最新更新