floatfil
floatfil

Reputation: 427

How to overload method

So I guess I was too vague with my question. I put together the runningTotal method at the end of the ArrayIntList class underneath and I'm asked to rewrite it as runningTotal(ArrayIntList) and static runningTotal(ArrayIntList), and implement all three, overloaded. Perhaps I'm confusing myself too much but I can't figure out where to go from here... I hope this is a bit clearer, thanks for all your help guys!

import java.io.*;

public class ArrayIntList {
    private int[] elementData;
    private int size;

    public ArrayIntList(){
        elementData = new int[100];
        size = 0;
    }

    public void add(int value){
        elementData[size] = value;
        size++;
    }

    public void print(){
        if (size == 0){
            System.out.println("[]");
        }
        else {
            System.out.print("[" + elementData[0]);
            for (int i = 1; i < size; i++)
                System.out.print(", " + elementData[i]);
            System.out.println("]");
        }
    }

    public ArrayIntList runningTotal() {
        ArrayIntList newList = new ArrayIntList();
        int i = 0;
        int total = 0;
        while (i < size) {

            total = elementData[i];
            for(int j = 0; j < i; j++);
            newList.add(total);
            i++;
        }
        return newList;
    }
}

Upvotes: 0

Views: 105

Answers (1)

Kirbinator
Kirbinator

Reputation: 213

What you have asked doesn't really make sense. I only count one runningTotal, and only one is called. You still have yet to write the others. Overloaded functions are just functions of the same name, usually with similar functionality, but set up differently. So:

void runningTotal(int valueIn)
{/*one thing*/}

void runningTotal(int[] arrayIn)
{/*another thing*/}

int runningTotal()
{return yetAnotherThing;}

...are all functions of the same name, but are all completely different functions. The power of this comes in the form of convenience, allowing you to pass a value to a function without heeding what type you are actually passing.

All you need to do is just define the function again. If there is functionality overlap, you can even call one of the other overloads from the overload you are writing.

The computer is looking at the parameter ordering most of the time. function(int, int) is different from function(string, int) or function(). The corollary to this is that it doesn't care about parameter names. function(int a, int b) is exactly the same as function(int c, int d), for example.

If you want to run these function literally at the same point in time, you should investigate Java Threads and Concurrency

Upvotes: 5

Related Questions