How Java accesses instance members of a class in a static method (a field or method with no static keyword attached)

Source: Internet
Author: User

How does Java access an instance member of a class in a static method (a field or method with no static keyword attached)?

Static modifiers are loaded at load time before non-static loading, that is, if a non-static method or variable is called in static, the non-static methods and variables do not exist at this time (this can be understood) .
Accessing an instance variable of a class in a static method requires first instantiating the class, and in addition to the static modification, you can first create an object that invokes the member methods and variables through the object, such as new A (). Test ().

For example:

 Packagestatic methods access instance variables; Public classtest{intA = 2;//instance Variable    Static intb = 3;//Static variables of the class     Public Static voidVariable ()//Static Methods{System.out.println ("Instance variable a =" +NewTest (). a); //accessing an instance variable of a class in a static method requires first instantiating the classSystem.out.println ("Static variable B =" +b); //Static variables of a class can be accessed directly in a static method    }      Public Static voidMain (string[] args) {test.variable (); Test test=NewTest (); System.out.println ("The result is: instance variable =" + test.a);//Accessing Instance members    }    }

The result is:

How Java accesses instance members of a class in a static method (a field or method with no static keyword attached)

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.