Calling a non-static method in a 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 include a non-static meth O to the static method, thus, wo can call the Non-static method in a indirect-in-a-do.
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); Static methods can be called directly in the main function
}
}

Calling a non-static method in a 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.