Home > Java > javaTutorial > How to use static modifier in java

How to use static modifier in java

PHPz
Release: 2023-05-15 23:34:04
forward
1505 people have browsed it

1. The static keyword is used to declare static variables independent of objects. No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also called class variables. Local variables cannot be declared as static variables.

2. The static keyword is used to declare static methods independent of objects.

Example

class InstanceCounter {
    private static int num = 540;  // 私有的静态变量
 
    public static int getNum(){    // 公有的静态方法
        return num;
    }
    
    // 构造方法 自动执行 构造方法中可以使用this 和es6中的构造函数一样
    public InstanceCounter() {     
        System.out.println(this.getNum()); // this.getNum() == getNum()  
        this.num++;   // this.num == num
    }
}
 
public class demo1{
    public static void main(String[] args) {
    
        new InstanceCounter();
        System.out.println(InstanceCounter.getNum());  // 打印静态方法 类名调用 541
    }
}
Copy after login

The above is the detailed content of How to use static modifier in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template