Question

Given the following program, finish the driver class to demonstrate polymorphism. Program: PolyMath Copy and paste your drive

I am having trouble understanding the concept of polymorphism. I know that I only need to edit the MathDriver.java (driver) class, but I am not entirely sure how.

Here is my MathDriver.java driver class, the one that I need to finish:

// Driver class public class MathDriver { public static void main(String[] args) { Math math; int[] array = {5, 6, 3, 4}; مہه

Here is the parent class, Math.java:

//Parent class of Addition, Multiplication, and Subtraction | public class Math { protected int[] array; protected int result

Lastly, here are the child classes, Addition, Subtraction, and Multiplication

// Child class of Math public class Addition extends Math { Addition(int[] array) { super(array); } public int nNumbers() { r//Child class of Math | public class Subtraction extends Math{ Subtraction(int[] array) { super(array); بہ public int nNumber//Child class of Math public class Multiplication extends Math { Multiplication (int[] array) { super(array); } public int nN

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

===========================================

JAVA PORGRAM

===========================================

/////MathDriver.java

import java.util.Arrays;

public class MathDriver
{
   public static void main(String[] args) {
       int[] array = {5,6,3,4};
       //print the given array of integers
       System.out.println("Te given array is : "+Arrays.toString(array));
      
       //Create a Math array named mathOperations of size 3
       //The purpose of this array is to hold 3 child class instances of Math class
       //Since Math is a parent class so it can hold its child class instances
       Math mathOperations[] = new Math[3];
      
       //All the below classes is instantitated through parameterized constructor
       //by passing the array
      
       //Create instance of Addition class(child of Math) and store it @ 0th index
       mathOperations[0] = new Addition(array);
       //Create instance of Subtraction class(child of Math) and store it @ 1st index
       mathOperations[1] = new Subtraction(array);
       //Create instance of Multiplication class(child of Math) and store it @ 2nd index
       mathOperations[2] = new Multiplication(array);
      
      
       //Traverse through each Math object of mathOperations
       for(Math operation: mathOperations){
       //Since operation (Math reference) is basically holding child class instances
       //hence through runtime polymorphism , nNumbers methods defined (overridden) in the
       //respective child class will be called and accordingly result will be fetched
       int result = operation.nNumbers();
      
       //check operation is instance of which child class through instanceof
       //and print the result accordingly
       if(operation instanceof Addition)
       System.out.println("Result of Addition = "+result);
       else if(operation instanceof Subtraction)
       System.out.println("Result of Subtraction = "+result);
       else if(operation instanceof Multiplication)
       System.out.println("Result of Multiplication = "+result);
       }
      
   }
}

//////Math.java

//Parent class
public class Math{
protected int[] array;
protected int result;
  
Math(int[] array){
this.array = array;
result = 0;
}
  
public int nNumbers(){
result = 0;
  
for(int i =0; i < array.length; i++){
result = array[i];
}
  
return result;
}
}

/////////Addition.java

//Child class Addition
public class Addition extends Math{
  
Addition(int[] array){
super(array);
}
  
//overridden nNumbers method for Addition
public int nNumbers(){
result = 0;
  
for(int i =0; i < array.length; i++){
result += array[i];
}
  
return result;
}
  
public String toString(){
return ""+result;
}
}

//////////Subtraction.java

//Child class Subtraction
public class Subtraction extends Math{
Subtraction(int[] array){
super(array);
}
//overridden nNumbers method for Subtraction
public int nNumbers(){
result = array[0];
  
for(int i =1; i < array.length; i++){
result -= array[i];
}
  
return result;
}
  
public String toString(){
return ""+result;
}
}

////////////////Multiplication.java

//Child class Multiplication
public class Multiplication extends Math{
Multiplication(int[] array){
super(array);
}
  
//overridden nNumbers method for Multiplication
public int nNumbers(){
result = 1;
  
for(int i =0; i < array.length; i++){
result *= array[i];
}
  
return result;
}
  
public String toString(){
return ""+result;
}
}

=========================================

OUTPUT

=========================================

Te given array is : [5, 6, 3, 4]
Result of Addition = 18
Result of Subtraction = -8
Result of Multiplication = 360

=============================================

EXPLANATION

=============================================

Please check the inline commentns given in the MathDriver.java. It has detailed explanation of where and how the polymorphism is being used.

Add a comment
Know the answer?
Add Answer to:
I am having trouble understanding the concept of polymorphism. I know that I only need to...
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
  • Hi, I am writing Java code and I am having a trouble working it out. The...

    Hi, I am writing Java code and I am having a trouble working it out. The instructions can be found below, and the code. Thanks. Instructions Here are the methods needed for CIS425_Student: Constructor: public CIS425_Student( String id, String name, int num_exams ) Create an int array exams[num_exams] which will hold all exam grades for a student Save num_exams for later error checking public boolean addGrade( int exam, int grade ) Save a grade in the exams[ ] array at...

  • please answer correctly. Language/Type Java Inheritance polymorphism Assume that the following classes have been defined: public...

    please answer correctly. Language/Type Java Inheritance polymorphism Assume that the following classes have been defined: public class George extends Elaine ( public void method1() { print("George 1 "); public class Jerry { public void method10) { print("Jerry 1 "); public void method20 { print("Jerry 2 "); public String toString() { return "Jerry": public class Elaine extends Kramer public String toString() { return "Elaine " + super.toString(); public class Kramer extends Jerry public void method1() { super.method1(); print ("Kramer 1"); public...

  • Write in java and the class need to use give in the end copy it is...

    Write in java and the class need to use give in the end copy it is fine. Problem Use the Plant, Tree, Flower and Vegetable classes you have already created. Add an equals method to Plant, Tree and Flower only (see #2 below and the code at the end). The equals method in Plant will check the name. In Tree it will test name (use the parent equals), and the height. In Flower it will check name and color. In...

  • I Have a problem with my JAVA class "Directivo". In the " public double sueldo() "...

    I Have a problem with my JAVA class "Directivo". In the " public double sueldo() " method, the instruction say "Calculate the salary of a Directivo the following way: Invoke method salary of the father and add him the extra bonus" My question is : How can I do this ? how can i implement that instruction in the public double sueldo() method public class Directivo extends Planta implements Administrativo{    private double bonoExtra;    public Directivo( String nom, String...

  • PLEASE HELP this is the last part of my lab and I need help ): add comments please (: if it is to...

    PLEASE HELP this is the last part of my lab and I need help ): add comments please (: if it is too difficult you do not have to do part 3 but it would be greatly appreciated if you do ! Obtain example code files Circle.java, Shape.java, CircleShape2.java, Sphere.java, and CircleShapeApp.java from the downloaded files in Ch8. Compile and execute the example and understand the polymorphism it performs. (I have copied and pasted all of these files below) Modify...

  • I am having trouble understanding how this code is able to use the contents of the...

    I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide comments in the main code to describe what is happening? (especially on the bool isNumber) THE MAIN CODE: #include<bits/stdc++.h> #include "MyCartesianPoint.h" #include <math.h> #include <iostream> using namespace std; bool isNumber(string s) {    if(!isdigit (s[0]))    {        if(s[0] != '-')        return false;               else if(s.length() == 1)        return false;...

  • I am having trouble understanding how this code is able to use the contents of the...

    I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide brief comments in the top code to show what is happening? THE CODE: #include<bits/stdc++.h> #include "MyCartesianPoint.h" #include <math.h> #include <iostream> using namespace std; bool isNumber(string s) {    if(!isdigit (s[0]))    {        if(s[0] != '-')        return false;               else if(s.length() == 1)        return false;    }       for...

  • In Java Create a testing class that does the following to the given codes below: To...

    In Java Create a testing class that does the following to the given codes below: To demonstrate polymorphism do the following: Create an arraylist to hold 4 base class objects Populate the arraylist with one object of each data type Code a loop that will process each element of the arraylist Call the first ‘common functionality’ method Call the second ‘common functionality’ method Call the third ‘common functionality’ method Verify that each of these method calls produces unique results Call...

  • Task 3: Main Program Create a main program class that: Creates three or more Nurse instances...

    Task 3: Main Program Create a main program class that: Creates three or more Nurse instances assigned to different shifts. Creates three or more Doctor instances. Creates three or more Patient instances with pre-determined names and manually assigned physicians chosen from the pool of Doctor instances previously created. Generates another 20 Patient instances using randomly generated names and randomly assigns them physicians chosen from the pool of Doctor instances previously created. Prints the toString() values for all employees. Prints the...

  • Hey guys I am having trouble getting my table to work with a java GUI if...

    Hey guys I am having trouble getting my table to work with a java GUI if anything can take a look at my code and see where I am going wrong with lines 38-49 it would be greatly appreciated! Under the JTableSortingDemo class is where I am having erorrs in my code! Thanks! :) import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; public class JTableSortingDemo extends JFrame{ private JTable table; public JTableSortingDemo(){ super("This is basic sample for your...

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