Consider two classes in a default package :
class Trial {
int a;
int b;
public static void main (String [] args){
System.out.println("test base");
}
}
public class TrialExe {
int a;
int b;
public static void main (String [] args){
Trial t = new Trial();
System.out.println("test exe");
}
}
Compiling TrialExe: javac TrialExe
How can this compile?. Considering that the Trial object is created from a static block, to create an object the constructor of Trial is required, but as far as I know we cannot access a non static method from a static method and the constructor is non static.
A static method cannot call a non-static method or field. That is correct.
But constructors are special. You can construct a new object from within a static method and then you can call that object's methods, even if they are not static and even if that object is an instance of the same class.
Think of it this way:
Because of this, you cannot call an instance method from a static method because there is no encapsulating instance. However, a static method can create an object and then call that instance's methods.
A static method cannot call a non-static method or field but a non-static method can call a static method or field.
Constructor is not same as other instance method, it is different. That's why you can create object within the static method.
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