0
点赞
收藏
分享

微信扫一扫

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


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

文章目录

​​深入了解关键词static​​

​​一、static修饰属性​​

​​二、static修饰方法​​

深入了解关键词static

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

一、static修饰属性

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);

}
}

内存分析:

大数据必学Java基础(三十六):深入了解关键词static_开发语言_02

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

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

static修饰属性总结:

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

(2)先于对象存在

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

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

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修饰方法

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();

}
}

  • 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
  • 📢本文由 Lansonli 原创,
  • 📢停下休息的时候不要忘了别人还在奔跑,希望大家抓紧时间学习,全力奔赴更美好的生活✨
举报

相关推荐

0 条评论