首页 > 其他 > 详细

static 关键字

时间:2021-04-10 01:02:15      阅读:24      评论:0      收藏:0      [点我收藏+]

static 关键字

  • 用static声明的成员变量为静态成员变量,也成为类变量。类变量的生命周期和类相同,在整个应用程序执行期间都有效。

  • 注意:

    • static修饰的成员变量和方法,从属于类
    • 普通变量和方法从属于对象
    • 静态方法不能调用非静态成员,编译会报错
public class Student extends Person{
    private static int age = 10; //静态变量
    private double score = 80.6;

    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student.age);
        System.out.println(student.score);
        System.out.println(Student.age);
        //System.out.println(Student.score);   不能直接用类名去调用非静态变量
    }
}

//10
80.6
10
public class Student extends Person{
    private static int age = 10; //静态变量
    private double score = 80.6;

    public static void print(){
        System.out.println("静态方法");
    }

    public void add(){
        System.out.println("非静态方法");
    }
    public static void main(String[] args) {
        Student student = new Student();
        Student.print();
        //Student.add();    不能直接用类名去调用非静态方法
        student.print();
        student.add();
    }
}
//静态方法
静态方法
非静态方法
public class Person {
    {
        //代码块(匿名代码块)
        System.out.println("代码块(匿名代码块)");
    }

    static {
        //静态代码块:只执行一次
        System.out.println("静态代码块");
    }

    public Person() {
        System.out.println("执行构造方法");
    }

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("================================");
        Person person1 = new Person();
    }
}

//静态代码块
代码块(匿名代码块)
执行构造方法
================================
代码块(匿名代码块)
执行构造方法

static 关键字

原文:https://www.cnblogs.com/saxonsong/p/14638143.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!