public class TestClass(){
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
Is it not
public class TestClass{
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
This is a perfectly valid code. When the main
method is called, no prior instance of the TestClass
exists (it needs not, because the main
method is static
).
public class Test2{
public Test2 clone(){
return new Test2();
}
}
This is perfectly valid as well. When you create a new instance of Test2, it contains the clone
method, but the method is not automatically executed. Only when the clone
method is called, one more instance of Test2 is created.
public class MyLinkedList{
MyLinkedList next;
MyLinkedList(int elems){
if(elems>0){
next = new MyLinkedList(elems-1);
}else{
next = null;
}
}
}
is perfectly valid as well, even if the constructor creates a new instance using the same constructor, because the creation is guarded by a conditional, so creating an instance sometimes triggers a new creation.
public class Fail{
public Fail(){
new Fail();
}
}
Is the only problematic example here. The compiler doesn't complain. It can be translated into byte code and it can be executed. At the runtime, however, you cause a stack overflow:
The compiler allows this, because, in general, the compiler cannot prevent all infinite recursion. The compiler allows anything that can be translated into bytecode.
The compiler, however, may issue a warning if it detects a method or a method chain calls itself unconditionally.