My Assumptions:
- Static method cannot cannot call non-static methods.
- Constructors are kind of a method with no return type.
Given this example…
public class Main {
public static void main(String[] args) {
Main p = new Main(); // constructor call
k(); // [implicit] `this` reference
}
protected Main() {
System.out.print("1234");
}
protected void k() {
}
}
- this line prints 1234:
Main p = new Main() - this line throws an Exception:
k()
Why did the example code do those two things? Don’t they conflict with my above Assumptions? Are my Assumptions correct?
Sure they can, but they need an object to call the method on.
In a static method, there’s no
thisreference available, sofoo()(which is equivalent tothis.foo()) is illegal.If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a
thisreference inside a constructor).Given this view, it should be clear to you why a static method can call a constructor without any problems.
So, to sum it up:
is okay, since
new Main()does not rely on any existing object.is not okay since it is equivalent to
this.k()andthisis not available in your (static) main method.