Exception in thread "main" java.lang.StackOverflowError
Hi,
Starting out with Java - have this test code but not working. Any ideas would be appreciated. Geeting the error:
Exception in thread "main" java.lang.StackOverflowError
importstatic java.lang.System.out;
publicclass Mtest{
publicint finalTime;
publicstaticvoid main(String[] args){
new Mtest();}
public Mtest(){
City paris =new City(5,"Paris");
out.println(paris.cityName +" " + paris.cityTime());
}
publicvoid twentyFourHourTime(){
finalTime = 7;
}
}
class City{
public String cityName;
publicint timeDiff;
Mtest timeRef;
public City (int t, String c){
timeDiff = t;
cityName = c;
}
publicint cityTime(){
timeRef =new Mtest();
int t = timeRef.finalTime - timeDiff;
return t;
}
}
[2125 byte] By [
Chumbya] at [2007-11-27 3:54:22]

The main method creates a new Mtest, which creates a new City and calls its cityTime method. cityTime creates a new Mtest object, which itself creates a new City and calls cityTime, which creates a new Mtest object which creates a new City and calls its cityTime method, which creates a new Mtest object which creates a new City and calls its cityTime method, which creates a new Mtest object which creates a new City and calls its cityTime method, which creates a new Mtest object which creates a new City and calls its cityTime method...
Take out the code that causes it.
In particular, ask yourself whether cityTest should really create Mtest objects.
That's the short answer. The longer answer is, if you can't completely remove the stuff that causes the loop, then create some kind of end conditions that terminate it. For example, perhaps Mtest could create a City object and invoke its cityTest method, and cityTest could either (1) not create any MTest objects at all, or it could create a version of Mtest that represents a test of the internals of cityTest, and which wouldn't create any more City objects.
Thanks for that...
I appreciate your help with.
I spose if I take a step back - I am sure how to get values from one class to another.This code was designed to try and test that but not working. My understanding was that I had to create a new object unless the class was static? But id I made it static then I get the static - non static error messages...
Thanks,
Chumby
You can easily pass data from one class to another, without creating new instances. Just invoke a method on the existing object, as in:
someObject.setValue(15);
If you really wanted to, you could do the same thing on a class level (as opposed to an instance level) by invoking static methods...but there's no need to worry about that now...
But keep in mind that in object-oriented programming, you try to avoid passing values around. The whole idea is to keep data encapsulated, which means that it's tightly associated with the operations that use or modify the data, and that the data is hidden from everything else. Of course, in the real world you can't get 100% encapsulation, but you can strive for it.