MENU

static 关键字

June 5, 2018 • Read: 2746 • Java阅读设置

1.static 作用

  1. 使用 static 声明属性
    使用 static 声明全局属性
  2. 使用 static 声明方法
    直接通过类名调用
  3. 注意点
    使用 static 方法的时候,只能访问 static 声明的属性和方法,而非 static 声明的属性和方法是不能访问的

2. 示例

  • class Person{
  • static String country = "北京";
  • }
  • public static void main(String args[]){
  • Person p1 = new Person();
  • System.out.println(p1.country);//北京
  • p1.country = "上海";//这样写可以,但不推荐
  • Person p2 = new Person();
  • System.out.println(p1.country);//上海
  • Person.country = "广州"//静态对象或方法一般用类名直接调用
  • Person p3 = new Person();
  • System.out.println(p3.country);//广州
  • }
Last Modified: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment