[Reprinted] Supplementary explanation on "static methods cannot call non-static methods"

Source: Internet
Author: User

I found an article to verify my previous ideas (the static method must call the non-static method by passing object parameters, because the non-static method corresponds to the object instance)

Http://hi.baidu.com/danghj/blog/item/1f96d1eac9771cd6d539c986.html

Call non-static methods in static methods

We all know that,Non-static non-static methods cannot be called in static methods.To be precise, the non-static method cannot be called directly. However, you can pass an object reference to the static method and call the non-static method of the object.

In fact, this fact is often applied, so we do not pay attention to it: in the main function (static method), we often create a class instance, and then use its drinking variables to call its non-static method. // Staticmethodtest. Java
// A ststic method cannot call a non-static method, but we can transfer a object reference, which include a non-static metho to the static method, thus, wo can call that non-static method in a indirect way. public class staticmethodtest {
Void nonstaticmethod (){
System. Out. println ("this is a non-sataic method .");}

Static void staticmethod (staticmethodtest s ){
System. Out. println ("this is a static method .");
S. nonstaticmethod ();
} Public static void main (string [] ARGs) {staticmethodtest sobj = new staticmethodtest ();
Staticmethod (sobj); // you can directly call the static method in the main function.
}
}

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.