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...

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

  • C# - Inheritance exercise I could not firgure out why my code was not working. I...

    C# - Inheritance exercise I could not firgure out why my code was not working. I was hoping someone could do it so i can see where i went wrong. STEP 1: Start a new C# Console Application project and rename its main class Program to ZooPark. Along with the ZooPark class, you need to create an Animal class. The ZooPark class is where you will create the animal objects and print out the details to the console. Add the...

  • I am working on this code and keep getting errors like "ERROR: Syntax error: Encountered "<EOF>"...

    I am working on this code and keep getting errors like "ERROR: Syntax error: Encountered "<EOF>" at line 1, column 169." and "ERROR: Table/View 'STUDENT' does not exist. ERROR: Table/View 'STUDENT' does not exist. ERROR: Table/View 'STUDENT' does not exist." I do not know why this isn't working. Here is my code: DTCCDatabase.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * This program creates the CoffeeDB database. */ public class DTCCDatabase {    public static void main(String[] args)...

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
ADVERTISEMENT