Home arrow static arrow Java Programming [Archive] - Why doesn't it matter whether I create an instance or not?
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Why doesn't it matter whether I create an instance or not?
This topic has 2 replies on 1 page.

Posts:22
Registered: 6/21/04
Why doesn't it matter whether I create an instance or not?  
Jun 28, 2004 7:11 PM



 
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[i]; 		}		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
 

Posts:1,183
Registered: 1/23/02
Re: Why doesn't it matter whether I create an instance or not?  
Jun 28, 2004 7:18 PM (reply 1 of 2)



 
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.

Please read the tutorial that I suggested previously.

http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
 

Posts:22
Registered: 6/21/04
Re: Why doesn't it matter whether I create an instance or not?  
Jun 28, 2004 11:20 PM (reply 2 of 2)



 
legosa,

Thanks for the pointer, I will read up on it straight away!

Regards

Davo
 
This topic has 2 replies on 1 page.