Static variables in C++ and Java

前端 未结 2 698
暖寄归人
暖寄归人 2021-02-14 17:27

I have a question: let\'s say we have this function: (in C++)

int& f() {
    static int x = 0;
    return x;
} // OK

and

i         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 18:16

    Static keyword is used for almost same purpose in both C++ and Java. There are some differences though.

    1) Static Data Members: Like C++, static data members in Java are class members and shared among all objects.

    2) Static Member Methods: Like C++, methods declared as static are class members and have following restrictions:

    • (i) They can only call other static methods.
    • (ii) They must only access static data.
    • (iii) They cannot access this or super

    Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using class name.

    3) Static Block: Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside static block is executed only once (first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class)).

    4) Static Local Variables: Unlike C++, Java doesn’t support static local variables. If used , Java program fails in compilation.

    5) Static class: Classes can also be made static in Java.In java, we can’t make Top level class static. Only nested classes can be static.

    • Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.
    • Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.

      Ref : www.geeksforgeeks.org

提交回复
热议问题