"Only static variables and static methods can be called in static methods"

Source: Internet
Author: User

Static methods can call static methods and static variables, but also non-static methods and non-static variables.

Public class test {public test () {}; public test (int I) {This. N = I;} public static int M = 5; Public int n = 10; Public void fun1 () {system. out. println ("non-static method fun1");} public static void fun2 () {system. out. println ("static method fun2");} // test "static methods can only call static variables and static methods". What does it mean: public static void main (string [] ARGs) {// No error will be reported when a static method is called // fun2 (); // when a static variable is called, system will not be reported. out. println (m); // The non-static method fun1 () // fun1 () cannot be referenced from the static context; // The non-static method cannot be referenced from the Static Context Non-static variable N // system. out. println (n); // you can call the non-static method constructor in the new object of the static method. The following code can be correctly executed no matter whether the default constructor is used or not. Therefore, "in the compilation stage, the compiler does not check the operations related to specific objects and objects in static methods ". In this way, a solution is provided to access non-static methods and non-static attributes in static methods. // Test T = new test (8); // T. fun2 (); // T. fun1 (); // system. out. println (T. m); // system. out. println (T. n );}}


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.