Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Code compiles and runs regardless of whether an instance is created!

Status
Not open for further replies.

JProg

Programmer
Apr 4, 2002
88
JP
Hey Everyone,

I have written a very simple class that finds the average of two sets of numbers. One set of numbers are ints whilst the other set are doubles! :)

The code works fine, and the method definitions are both static. The thing is that I forgot to access the methods in a "static" fashion. Instead I created an instance as I would normally, and accessed the static methods using this instance. The code is as follows:

/*

Surprisingly this class worked both with an instance and without!

*/

class ExerciseNinePointOne
{
public static void main(String[] args)
{
//ExerciseNinePointOne myExercise = new ExerciseNinePointOne();
int[] myInts = {1, 10, 15};
double[] myDoubles = {1.4, 0.22, 3.145};

//int myAvgInt = myExercise.intAvg(myInts);
//double myAvgDouble = myExercise.doubleAvg(myDoubles);

int myAvgInt = ExerciseNinePointOne.intAvg(myInts);
double myAvgDouble = ExerciseNinePointOne.doubleAvg(myDoubles);

System.out.println("Average for ints is: " + myAvgInt);
System.out.println("Average for doubles is: " + myAvgDouble);
}

public static int intAvg(int[] ints)
{
int divIntArray = ints.length;
int intSum = 0;
for(int i=0; i<ints.length; i++)
{
intSum = intSum + ints;
}
int intTotal = intSum / divIntArray;
return intTotal;
}

public static double doubleAvg(double[] doubles)
{
int divDoubleArray = doubles.length;
double doubleSum = 0.0;
for(int j=0; j<doubles.length; j++)
{
doubleSum = doubleSum + doubles[j];
}
double doubleTotal = doubleSum / divDoubleArray;
return doubleTotal;
}
}

Could somebody please explain to me why this code works "both ways", as in when I don't define an instance and when I do (commented sections). Thanks heaps for your help.

Regards

Davo
 
Its just part of the Java Language Specification. You may call static mathods from an explicitly instantiated object, or using the static class call - ie :

new Test().sayHello();

or

Test.sayHello();

What the difference is for the programmer though, I',m unsure of !

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top