首页 > 编程 > C++ > 正文

key word 'static' in c++/java

2019-11-11 05:40:57
字体:
来源:转载
供稿:网友

   古人云“温故而知新”,我挺喜欢这句话的,不过若不温故,就遗忘了,更何况知新?

Comparison of static keyWord in C++ and java

Static keyword is used for almost same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java.

Static Data Members: Like C++, static data members in Java are class members and shared among all objects. For example, in the following Java PRogram, static variable count is used to count the number of objects created.

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

1) They can only call other static methods. For example, the following program fails in compilation. fun() is non-static and it is called in static main()

2) They must only access static data.

3) They cannot access this or super . For example, the following program fails in compilation.

Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using class name. For example, in the following program, static data member count and static method fun() are accessed without any object.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. See Static blocks in Java for details.

Static Local Variables: Unlike C++, Java doesn’t support static local variables. For example, the following Java program fails in compilation.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选