ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【学习笔记】Static关键字

2022-07-18 16:01:09  阅读:112  来源: 互联网

标签:Person 静态 void 笔记 关键字 static Student Static public


Static关键字

static 用来修饰属性和方法

属性:

静态的属性可以直接调用

package com.oop.demo06;
​
public class Student {
    private static int age;
    private String name;
​
    public static void main(String[] args) {
        Student.age = 10;
    }
}
​

非静态的属性需要 实例化一个对象,在去调用

package com.oop.demo06;
​
public class Student {
    private static int age;
    private String name;
​
    public static void main(String[] args) {
        Student.age = 10;
       Student student = new Student();
       student.name = "zs";
    }
}

 

静态和非静态的方法与属性相同

package com.oop.demo06;
​
public class Student {
    public void run(){
​
    }
    public static void go(){
​
    }
    public static void main(String[] args) {
        //静态
       go();
       //或者  Student.go();
        
        //非静态
        Student student = new Student();
        student.run();
    }
}

 

静态代码块

除了属性和方法有静态之外,还有静态代码块,他在类一创建就创建了,并且在构造方法之前,并且只执行一次

package com.oop.demo06;
​
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();
    }
}

image-20220718154159369

 

我们可以看到程序先执行了静态代码块,然后是匿名代码块,最后是构造方法

我们在实例化一个对象

package com.oop.demo06;
​
public class Person {
    public Person() {
        System.out.println("构造方法");
    }
    {
        System.out.println("匿名代码块");
    }
    static {
        System.out.println("静态代码块");
    }
​
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("=================");
        Person person1 = new Person();
    }
}
​

image-20220718154417382

 

可以看到静态代码块只执行1次

匿名代码块可以用来赋一些初始值

 

其他用法

我们如果想要调用Math类中的random方法,一般是这么写:

package com.oop.demo06;
​
public class Test {
    public static void main(String[] args) {
        double num = Math.random();
    }
}
​

使用static,可以这样操作

package com.oop.demo06;
​
import static java.lang.Math.random;
public class Test {
    public static void main(String[] args) {
        double num = random();
    }
}
​

这叫做静态导入包

 

被final修饰的类,不能被其他类继承

标签:Person,静态,void,笔记,关键字,static,Student,Static,public
来源: https://www.cnblogs.com/wztblogs/p/16490753.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有