Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Java homework

Tags:

java

I know this is simple but I don't really understand the 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? Maybe I'm just looking into the question too much.

like image 536
Eric Smith Avatar asked Mar 12 '12 22:03

Eric Smith


People also ask

Can a 8 year old learn Java?

For this reason, children as young as 7 can be introduced to coding and Java, especially if they have expressed interest in wanting to learn them. However, most young children will benefit from learning coding by using visual block coding apps first.


4 Answers

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
like image 106
Ryan Amos Avatar answered Oct 11 '22 08:10

Ryan Amos


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

like image 34
dann.dev Avatar answered Oct 11 '22 08:10

dann.dev


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.

like image 37
Mark Byers Avatar answered Oct 11 '22 06:10

Mark Byers


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

like image 37
dsynkd Avatar answered Oct 11 '22 08:10

dsynkd