Questions about non-static method calls from Java static methods

Asked 2 years ago, Updated 2 years ago, 24 views

I'm not sure why static methods can't call non-static methods or instance variables.

java

2022-09-22 08:56

2 Answers

The non-static method rises to memory when you create an instance with that class.

Static methods go up together when class data goes up in memory.

Static methods can be invoked without an instance because they are already memory-up, but at that moment, we do not know whether the static method is also memory-up, so we have prevented them from calling non-static methods.


2022-09-22 08:56

If you can read the byte code, you can understand it by looking at the byte code.

But actually, if I could read the byte code, I wouldn't have posted the question in the first place.

In object-oriented language, there is something called this.

c++, java is this, and python is the first argument, usually using self.

The big difference is that the static method does not use this.

Instance methods cannot be invoked directly from static methods because this(aload_0) is not used.

If you are a Java developer, make sure to learn that jvm executes byte code.

The simple answer to the question is that the byte code has the aload_0 value as an instance variable, and the instance method assumes that the aload_0 value is always present in the variable array.

On the other hand, the static method does not call the constructor, so the value of aload_0 is the first variable value. This means that the instance method cannot be called directly from the static method because there is no this and the variable array does not have this.


2022-09-22 08:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.