Frage

Out of curiosity I came to write the following method:

public Object getObject() {
    return this.getObject();        
}

Why would Java allow me to write this? This method would never return any Object and would result in a StackOverflow Error.

War es hilfreich?

Lösung

1. I don't think compiler will have any objection in giving a clearance on your above code..i think its just how recursion is written and used.

2. Here this code will cause a problem during runtime, and so its entirely a problem with logic that the programmer has written, so it won't bother the compiler, but during runtime the Error will be thrown......

If compilers would have been this smart..... then Terminator movie would have been a near reality.....

Andere Tipps

It shouldn't stop you from doing it - this is just bottomless recursion, but it could've been a regular one. The compiler doesn't need to go and understand to code to guess if it's properly defined recursion or not.

Thing's like this always cause errors at runtime (as opposed to compile time). There are many instances in which something similar (in terms of recursion) could have be done which would have been perfectly valid.

Java has no notion of whether or not your code makes sense or not. If you decide you want to have a method call itself without an exit condition it will recurse until it runs out of stack space.

Without the ability for methods to call themselves, recursion would not be possible.

On a lighter note, a sane developer who extends the class that has this method might do something useful, since the method is anyway public. So the compiler need not object ;-)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top