Eric Smith
Eric Smith

Reputation: 1376

What different methods exist for invoking xMethod?

I know this is simple, but I don't really understand the homework-question:

Assume the signature of the method xMethod is as follows. Explain two different ways to invoke xMethod:

public static void xMethod(double[] a)

I thought to invoke a method you just do:

xMethod(myarray);

What could it mean by asking two different ways?

Upvotes: 5

Views: 1296

Answers (5)

dann.dev
dann.dev

Reputation: 2494

If this is for a first time java class, my guess is he is looking for these 2 cases:

//the one you have, using a precreated array
double[] myArray = {1.1, 2.2, 3.3}
xMethod(myarray);

//and putting it all together
xMethod(new double[]{1.1, 2.2, 3.3});

Basically illustrating you can make an array to pass, or simply create one in the call.

Just a guess though

Upvotes: 7

dsynkd
dsynkd

Reputation: 2145

static methods are not bound to the construction of the class. The method above can be called either by constructing the class or just by using the namespace:

Classname myclass = new Classname();
myclass.xMethod(myarray);

or you could just do:

Classname.xMethod(myarray);

as you see, you don't have to construct the class in order to use the method. On the other hands, the static method can't access non-static members of the class. I guess that's what the question meant by 2 different ways...

Upvotes: 2

Ryan Amos
Ryan Amos

Reputation: 5452

For kicks, show your professor this:

XClass.class.getMethod("xMethod", a.getClass()).invoke(null, a);

Then tell them the two answers are

XClass.xMethod(a);
//and
xObject.xMethod(a); //this is bad practice

Upvotes: 10

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

There is only one valid way to do this:

YourClass.xMethod(myDoubleArray);

But, you can write non-totally-correct Java:

YourClass instance = new YourClass();
instance.xMethod(myDoubleArray);

This will work, but is considered as wrong. The Java compiler will even complain about it. Because a there is no need of invoking a static method by creating an instance of the class. Static means that the method is instance independent. Invoking it through an instance is pointless and confusing.

Later on, you will see that there is a second correct way of doing it, ie "reflection". But that is an advanced topic, so I assume you are not supposed to know this already.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839114

You could invoke it either by calling it on a class, or via an instance of that class.

Foo.xMethod(a);

or:

Foo foo = new Foo();
foo.xMethod(a);

The first approach is prefered, but the second one will compile and run. But be aware that it is often considered a design flaw in the language that the second approach is allowed.

Upvotes: 3

Related Questions