Java: Iterative method returning an object

Out of curiosity, I came to write the following method:

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

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

+4
source share
5 answers

1. I can’t think that the compiler will have any objection to granting permission to your code above. I think its just how recursion is written and b.

2. Here, this code will cause a problem during runtime , and therefore it is completely a problem with the logic written by the programmer, so it will not bother the compiler, but at runtime the Error will be thrown ...

If the compilers were so smart ..... then the Terminator movie would be a close reality .....

0
source

This should not stop you from doing this - it’s just a bottomless recursion, but it could be normal. The compiler does not need to go and understand the code in order to guess whether the recursion is defined correctly or not.

+6
source

This situation always causes runtime errors (as opposed to compile time). There are many examples in which one could do something similar (in terms of recursion), which would be completely correct.

+2
source

Java has no idea whether your code makes sense or not. If you decide that you want the method call to be executed without an exit condition, it will return until the stack space runs out.

Without the ability of methods to call themselves recursion is impossible.

+1
source

In a lighter note, a smart developer who extends the class that has this method can do something useful, since the method is publicly available anyway. Therefore, the compiler does not need an object; -)

0
source

Source: https://habr.com/ru/post/1433224/


All Articles