怕什么真理无穷

导航

关于static之静态变量和静态方法的简单理解

//1.静态变量
class Student{
    static String schoolName;//静态变量,只能定义类成员变量,不能定义局部变量,否则报错
}
public class Example7{
    public static void main(String[] args){
        Student stu1=new Student();
        Student stu2=new Student();
        Student.schoolName="哈佛大学";//静态变量,可以直接通过它所在的类名+变量名调用并赋值,类名.静态变量名
        System.out.println("我的学校是"+stu1.schoolName);
        System.out.println("我的学校是"+stu2.schoolName);
        Person.sayHello();//调用下边的静态方法,可以不用new一个对象,直接类名.方法名调用,这是static的特性
        }
    }

//2.静态方法
class Person{
    public static void sayHello(){ //静态方法,已在如上类中通过类名.方法名调用
        System.out.println("Hello!");
    }
}

 

posted on 2021-01-25 22:44  惭愧书生  阅读(157)  评论(0)    收藏  举报