前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >大数据必学Java基础(三十六):深入了解关键词static

大数据必学Java基础(三十六):深入了解关键词static

原创
作者头像
Lansonli
发布2022-08-01 00:27:31
1590
发布2022-08-01 00:27:31
举报
文章被收录于专栏:Lansonli技术博客

​深入了解关键词static

static可以修饰:属性,方法,代码块,内部类。

一、static修饰属性

代码语言:javascript
复制
package com.lanson;

/**
 * @Auther: lanson
 */
public class Test {
    //属性:
    int id;
    static int sid;

    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        //创建一个Test类的具体的对象
        Test t1 = new Test();
        t1.id = 10;
        t1.sid = 10;

        Test t2 = new Test();
        t2.id = 20;
        t2.sid = 20;

        Test t3 = new Test();
        t3.id = 30;
        t3.sid = 30;

        //读取属性的值:
        System.out.println(t1.id);
        System.out.println(t2.id);
        System.out.println(t3.id);

        System.out.println(t1.sid);
        System.out.println(t2.sid);
        System.out.println(t3.sid);

    }
}

内存分析:

一般官方的推荐访问方式:可以通过类名.属性名的方式去访问

static修饰属性总结:

(1)在类加载的时候一起加载入方法区中的静态域中

(2)先于对象存在

(3)访问方式: 对象名.属性名 类名.属性名(推荐)

static修饰属性的应用场景:某些特定的数据想要在内存中共享,只有一块 --》这个情况下,就可以用static修饰的属性

代码语言:javascript
复制
package com.lanson;

/**
 * @Auther: lanson
 */
public class LansonStudent {
    //属性:
    String name;
    int age;
    static String school;

    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        LansonStudent.school = "育英中学";
        //创建学生对象:
        LansonStudent s1 = new LansonStudent();
        s1.name = "张三";
        s1.age = 19;
        //s1.school = "育英中学";

        LansonStudent s2 = new LansonStudent();
        s2.name = "李四";
        s2.age = 21;
        //s2.school = "育英中学";

        System.out.println(s2.school);




    }

}

属性:

静态属性 (类变量)

非静态属性(实例变量)

二、static修饰方法

代码语言:javascript
复制
package com.lanson;

/**
 * @Auther: lanson
 */
public class Demo {
    int id;
    static int sid;

    public void a(){
        System.out.println(id);
        System.out.println(sid);
        System.out.println("------a");
    }
    //1.static和public都是修饰符,并列的没有先后顺序,先写谁后写谁都行
    static public void b(){
        //System.out.println(this.id);//4.在静态方法中不能使用this关键字
        //a();//3.在静态方法中不能访问非静态的方法
        //System.out.println(id);//2.在静态方法中不能访问非静态的属性
        System.out.println(sid);
        System.out.println("------b");
    }

    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        //5.非静态的方法可以用对象名.方法名去调用
        Demo d = new Demo();
        d.a();
        //6.静态的方法可以用   对象名.方法名去调用  也可以 用  类名.方法名 (推荐)
        Demo.b();
        d.b();

    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ​深入了解关键词static
    • 一、static修饰属性
      • 二、static修饰方法
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档