My Assumptions:
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() {
}
}
Main p = new Main()
k()
Why did the example code do those two things? Don't they conflict with my above Assumptions? Are my Assumptions correct?
Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.
A static constructor doesn't take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).
Where the "super" keyword in Java is used as a reference to the object of the superclass. This implies that to use "super" the method should be invoked by an object, which static methods are not. Therefore, you cannot use the "super" keyword from a static method.
The constructors in Java can not be static because if the constructors are marked as static, they can not be called from the child class; thus, the child class's object will not be created. The program will not be compiled and throw a compile-time error.
No. Constructors aren't ordinary methods in this respect. The whole point of the constructor is to, well, construct a new instance of the class.
So it can be invoked in static scope too. Just think about it: if you needed an existing instance of your class in order to create a new instance of it, you would simply never be able to instantiate it ever.
A few clarifications:
Static method cannot cannot call non-static methods.
Not quite. You can call a nonstatic method from inside a static method, just you need to scope it to a specific object of that class. I.e.
p.k();
would work perfectly in your code sample above.
The call
k();
would be fine inside an instance (nonstatic) method. And it would be equivalent to
this.k();
The implied this
refers to the current instance of the class. Whenever the compiler sees an unqualified call like k()
within an instance method, it will automatically scope it with this.
. However, since static methods aren't tied to any instance of the class, you (and the compiler) can't refer to this
inside a static method. Hence you need to explicitly name an instance of the class to call an instance method on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With