Chris Miller
Chris Miller

Reputation: 31

Java Method Stub

Teacher proposed these questions:

Assume that the following is called from a main method, write a method stub for this invocation: String course = "band";int year = 2016;printRoster(course,year)

Assume that the following is called from a main method, write a method stub for this invocation: String item = enterDescription();

With no other information, I am slightly confused on what he wants and means by write a method stub. Help would be greatly appreciated!

Upvotes: 1

Views: 17939

Answers (2)

Zircon
Zircon

Reputation: 4707

A method stub, likely referring to a method signature, is comprised of an access type, return type, other keywords, the method name, and its parameters. For example, the method stub for the main method is:

public static void main(String[])

Your teacher is asking you to use the context of the code snippet to determine what the method stub would look like. For example, if I had a method called like this:

int num = getNum();

Then I know:

1) This is inside the main method, which is static, and so the getNum method must also be static.

2) the getNum method returns an int because it is being assigned to that type of variable.

3) No arguments are being passed to getNum, so it has no parameters.

As such, I would guess that the method signature for getNum() is:

static int getNum()

This is because I don't know if getNum is public, private, etc.

Hopefully this helps you understand the problem and solve it on your own.

Upvotes: 3

ManoDestra
ManoDestra

Reputation: 6473

I assume he means that you will need to write a method stub for the calls in the code:

String course = "band";
int year = 2016;
printRoster(course, year);

And...

String item = enterDescription();

Therefore...

private void printRoster(String course, int year) {
    // For example...
    System.out.println("Course: " + course);
    System.out.println("Year: " + year);
}

private String enterDescription() {
    // Mocked return
    return "foobar";
}

Unless he means stub out the code itself, which would then be...

private void doSomething() {
    String course = "band";
    int year = 2016;
    printRoster(course, year);
}

private void doSomethingElse() {
    String item = enterDescription();
}

I suspect it is the former though.

And NB, if the methods are called from a static context, then they should also be declared as static, unless you're going to instantiate the object on which they will be called first.

Upvotes: -1

Related Questions