Statically static keywords in Java

Source: Internet
Author: User

A static member function of a class cannot access non-static member functions and non-static member variables.

But the reverse is true.

That is, non-static member functions can access static member functions and static member variables.

This can be explained by the characteristics of static members, because static members belong to classes, so even objects without classes we can access static members of the class.

A non-static member function, however, can only be accessed through the object of the class, so it must have an object.

So, the rebuttal method:

If the static member function of a class can access non-static member functions: The sample code is as follows,

 class   test{ public  static  int      I;  private  int      J;  public  static  void   ff () {GG ();         //  static member functions cannot access non-static member functions     System.out.println ("Static member function"  public  void   Gg () {System.out.println (" non-static member function "

When we do not create an object, we use the class name to access the FF ()

Test.ff ();

This is a mistake, and in fact it was not compiled before the eclipse.

Cannot make a static reference to the Non-static method GG () from the type Test

So what's the use of the static keyword?

We can use the Static keyword to restrict the object of a class to only one , and the code is as follows:

 PackageTesthello;classtest{Private  inti; Private StaticTest test =NewTest (); PrivateTest () {} Public StaticTest Gettest ()//here the Static keyword can not be less, you can not access the above test member variables    {        returntest; }         Public voidSetiintnum) {i=num; }         Public intGeti () {returni; }    } Public classhelloworld{ Public Static voidMain (string[] args) {Test T=test.gettest (); T.seti (10);    System.out.println (T.geti ()); }}

Statically static keywords in Java

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.