Question

The following code has a problem with polymorphism. I keep getting a runtime error. Error: "An...

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;

       }

    }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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();

}

}

Add a comment
Know the answer?
Add Answer to:
The following code has a problem with polymorphism. I keep getting a runtime error. Error: "An...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Aditya is a co-worker of yours at Company ABC. Aditya has a problem with his C#...

    Aditya is a co-worker of yours at Company ABC. Aditya has a problem with his C# code caused by his use of Polymorphism. The code can be compiled but is throwing a runtime error as shown below. Could you help Aditya to figure out what is the reason? State what the problem is and add one line of code to correct the problem. C# Code: class Sensor     {         private string sensorName;         public Sensor(string _name)         {            ...

  • What is wrong with this Code? Fix the code errors to run correctly without error. There...

    What is wrong with this Code? Fix the code errors to run correctly without error. There are seven parts for one code, all are small code segments for one question. All the 'pets' need to 'speak', every sheet of code is connected. Four do need need any Debugging, three do have problems that need to be fixed. Does not need Debugging: public class Bird extends Pet { public Bird(String name) { super(name); } public void saySomething(){} } public class Cat...

  • I need help with my code. It keeps getting this error: The assignment is: Create a...

    I need help with my code. It keeps getting this error: The assignment is: Create a class to represent a Food object. Use the description provided below in UML. Food name : String calories : int Food(String, int) // The only constructor. Food name and calories must be // specified setName(String) : void // Sets the name of the Food getName() : String // Returns the name of the Food setCalories(int) : void // Sets the calories of the Food...

  • Hi ! I need help please, I want to write java code, but that is difficult...

    Hi ! I need help please, I want to write java code, but that is difficult for me. it is about using annotation, reflection and XLM_ file. Please help me! I want explaintion with code and I want to se result please! My assignment is! Using the annotations and reflection API write an XML file exporter for composite objects of any kind. That is, the exporter should rely only on the annotations in the class definitions of the composite objects...

  • Examples: Example 1-Runtime Polymorphism: Lets say we have a class Animal that has a method sound()....

    Examples: Example 1-Runtime Polymorphism: Lets say we have a class Animal that has a method sound(). Since this is a generic class so we can't give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message public class Animal public void sound System.out.println("Animal is making a sound"); Now lets say we a subclass of Animal class. Horse that extends Animal class. We can provide the implementation to the same method like this: class Horse extends...

  • What is wrong with this Code? Fix the code errors to run correctly without error. There...

    What is wrong with this Code? Fix the code errors to run correctly without error. There are four parts for one code, all are small code segments for one question. public class StudentTest { public static void main(String[] args){ // Part Time Student Test Student ft1 = new PartTimeStudent("George", "Bush", "123-12-5678", 1, 2 ); System.out.println(ft1); Student ft2 = new PartTimeStudent("Abraham", "Lincoln", "001-90-5323", 6, 22 ); System.out.println(ft2); // Full Time Student Test Student pt1 = new FullTimeStudent("Nikola", "Tesla", "442-00-0998", 8, 26...

  • What is wrong with this Code? Fix the code errors to run correctly without error. There...

    What is wrong with this Code? Fix the code errors to run correctly without error. There are two parts for one code (one question) the two parts branch off, one part has 2 sheets of code, the other has 3 sheets of code, all are small code segments for one question. Pt.1 - 2 sheets of code: public class Computer { private String make; private String type; private String modelNumber; private double cpuSpeed_GHz; private int ramSize_GB; private int hardDriveSize_GB; private...

  • I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label;...

    I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Fall_2017 {    public TextArea courseInput;    public Label textAreaLabel;    public JButton addData;    public Dialog confirmDialog;    HashMap<Integer, ArrayList<String>> students;    public Fall_2017(){    courseInput = new TextArea(20, 40);    textAreaLabel = new Label("Student's data:");    addData = new JButton("Add...

  • In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static...

    In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static void main(String[] args) { String[] equations ={"Divide 100.0 50.0", "Add 25.0 92.0", "Subtract 225.0 17.0", "Multiply 11.0 3.0"}; CalculateHelper helper= new CalculateHelper(); for (int i = 0;i { helper.process(equations[i]); helper.calculate(); System.out.println(helper); } } } //========================================== public class MathEquation { double leftValue; double rightValue; double result; char opCode='a'; private MathEquation(){ } public MathEquation(char opCode) { this(); this.opCode = opCode; } public MathEquation(char opCode,double leftVal,double rightValue){...

  • What kind of error is it when your program has a syntax error? Exception Logic error...

    What kind of error is it when your program has a syntax error? Exception Logic error Run-time error Compile-time error ----------------------- Consider the following code snippet: public class Employee { private String empID; private boolean hourly; public Employee(String employeeID, boolean isHourly) { . . . } } Which of the following statements can be used to create an object of type Employee? Employee anAuto = new Employee("10548", true); Employee anAuto = new Employee("10548", "true"); Employee anAuto = new Employee(10548, true);

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT