概述:
是一个静态修饰符关键字,表示静态的意思,可以修饰成员变量和成员方法以及代码块
特点:
被static修饰的成员变量是属于类的,叫做静态成员变量/类变量,会被该类的所有对象共有
使用:
一、static 修饰的成员变量
class Person {
// 定义成员变量
String name;
// 定义静态成员变量
static String country;
public Person(){}
public Person(String name,String country){
this.name = name;
this.country = country;
}
}
public class Tests {
public static void main (String[] args) {
// 实例化一个person对象,并传两个参数过去
Person p = new Person("张三","中国");
System.out.println(p.name + "," + p.country);
Person p2 = new Person();
// 当成员变量country被static修饰的话,会被该类的所有对象共享
System.out.println(p2.name + "," + p2.country);
}
}
输出结果:
对比两次输出结果,不难看出,被static修饰的变量会被该类的其它对象所调用
二、static修饰成员方法
class Person {
//非静态方法
public void method1(){
System.out.println("Person method1");
}
//静态方法
public static void method2(){
System.out.println("Person method2");
}
}
public class Tests {
public static void main (String[] args) {
/*
* static修饰成员方法:
* 格式:权限修饰符 static 返回值类型 方法名称(方法列表){方法体}
* 特点:被static修饰的成员方法叫做静态成员方法/类方法
* 使用:
* 对象名.静态成员方法(实参)--> 不推荐
* 类名称.静态成员方法(实参)--> 推荐使用
* */
// 实例化一个Person对象
Person person = new Person();
person.method1();
person.method2();
//推荐:类名称调用类方法
Person.method2();
}
}
static修饰的成员方法在调用时可以直接用 类名称.静态成员方法 ,这样使用会更便捷
不用再创建对象了,可以直接调用