Java static method call non-static method

Source: Internet
Author: User

As we all know, statically static methods cannot call the non-static Non-static method, which is exactly the way that the Non-static method cannot be called directly. However, you can call the object's Non-static method by passing a reference to the object into the static method. In fact, the      application of this fact is so often that we do not pay attention to it: in the main function (static method) We often create an instance of a class, and then use its drinking variable to invoke its non-static method. staticmethodtest.java//a Ststic method cannot call A Non-static method, but we can transfer A object reference, which in Clude a non-static Metho to the static method, thus, wo can call that non-static method in a indirect way.public class Sta ticmethodtest{    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);  The static method can be called directly in the main function    }}



========================================
The following code can be called:


=======================
The following method cannot be called:



Java static method call non-static method

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.