Why a Java static method cannot access a non-static method

Source: Internet
Author: User

A non-static method (without static) can access static methods (with static), but not in the opposite way, why not?

public class test{public void static main (String args[]) {method ();//error, prompting you to change method to static method2 ();//Call method correct new Test2 ( ). method (); Correct}public void method () {System.out.println ("HelloWorld");} public static void Method2 () {System.out.println ("HelloWorld");}} public class Test2{public void method () {System.out.println ("HelloWorld");}}

This is to be analyzed from the memory mechanism of Java, first, when you new an object, not first in the heap to open up memory space for the object, but first the static method in the class (static function with static modifier) loaded into a place called the method area, and then create the object in the heap memory. Therefore, static methods are loaded as the class loads. When you new an object that exists in memory, the This keyword generally refers to the object, but it is also possible to invoke the static method of the class with the class name without the new object.

The program is ultimately executed in memory, the variables are accessed only in memory, the static members of the class (Metamorphosis and methods) belong to the class itself, when the class is loaded with memory, can be directly accessed through the class name, non-static members (variables and methods) belong to the object of the class, So the memory is allocated only when the class object is created, and then accessed through the object of the class.

Accessing a non-static member in a static member of a class can be an error because a static member already exists when the non-static member of the class does not exist, and accessing something that does not exist in memory is of course an error.

When did the class get loaded? is loaded when a call is required.


Why a Java static method cannot access a non-static method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.