The following code has a problem with polymorphism. I keep getting a runtime err
ID: 3726483 • Letter: T
Question
The following code has a problem with polymorphism. I keep getting a runtime error.
Error: "An unhandled exception of type System.InvalidCastException occured in polymorphism.exe"
Apparently, I need one line of code to fix it.
C# Code:
class Sensor
{
private string sensorName;
public Sensor(string _name)
{
sensorName = _name;
}
public virtual void ActionType()
{
Console.WriteLine("Sensor Detect Nothing.");
}
}
class SmokeSensor : Sensor
{
private string type;
public SmokeSensor(string _type, string _name) : base(_name)
{
type = _type;
}
public override void ActionType ()
{
Console.WriteLine("Somke Sensor Detect Smoke.");
}
}
class Program
{
static void Main(string[] args)
{
Sensor super1, super2;
SmokeSensor sub1, sub2;
super1 = new Sensor("Sensor");
sub1 = new SmokeSensor("Smoke", "Smoke Sensor");
super2 = super1;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \Tip: this is where the code should go.
sub2 = (SmokeSensor)super1;
}
}
Explanation / Answer
One line of code is :
super1 =(Sensor)sub1;
using System;
class Sensor
{
private string sensorName;
public Sensor(string _name)
{
sensorName = _name;
}
public virtual void ActionType()
{
Console.WriteLine("Sensor Detect Nothing.");
}
}
class SmokeSensor : Sensor
{
private string type;
public SmokeSensor(string _type, string _name) : base(_name)
{
type = _type;
}
public override void ActionType ()
{
Console.WriteLine("Somke Sensor Detect Smoke.");
}
}
class Program
{
static void Main(string[] args)
{
Sensor super1, super2;
SmokeSensor sub1, sub2;
super1 = new Sensor("Sensor");
super1.ActionType();
sub1 = new SmokeSensor("Smoke", "Smoke Sensor");
sub1.ActionType();
super2 = super1;
super2.ActionType();
super1 =(Sensor)sub1;
super1.ActionType();//When a derived class overrides a virtual member,
//that member is called even when an instance of that class is being accessed
//as an instance of the base class
sub2 = (SmokeSensor)super1;
sub2.ActionType();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.