JAVA——static关键字

一、static关键字的应用场景

针对某一个变量属于类而不属于某一个具体的对象的时候,可以考虑使用static关键字

 二、 static概述:

多个对象共享同一份数据

三、static的特点及使用方法

1.static修饰的变量又称为共享变量,类变量,静态变量

2.静态成员属于某一类的,而不属于某一个具体的对象

3.访问静态成员的方式:

a.通过对象访问, 但不建议这样做,因为会对与其共享的同一静态变量的对象造成影响

b.通过类名访问

c.通过读(get)、写(set)方法访问

4.静态static关键字可以修饰变量,还能够修饰方法,同时还可以修饰代码块

5.static修饰的方法称为类方法,方法体内部称为静态环境/静态上下文

a.非静态环境可以访问静态变量

b.静态环境下只能够访问静态变量

c.静态环境下不能够出现this,super光健字

6.静态修饰方法的意义

意义:主要用于简化代码

a.静态方法用来访问静态成员

b.编写工具类;例如Arrays 工具类、 Math 工具类

1.构造方法私有

2.成员方法添加static关键字修饰

7.static还可以修饰类,但是必须是内部类

8.static的内存图

static是共享的,不变的,放在方法区,静态代码块在类加载的时候就会执行,并且只执行一次

四、代码演示

public class StaticDemo01 {

public static void main(String[] args) {

Student.country = “中国”;

Student s1 = new Student(“张三”, 18); //创建对象并通过下面的无参构造方法赋值

Student s2 = new Student(“李四”, 20);

Student s3 = new Student();

s1.show(); // 调用show方法

s2.show();

s3.show();

/**(下方s1、s2、s3共享同一静态成员变量“country”,通过对象s2将“美国”赋值给共享成员变量后 ,s1和s3再调用 country时, 得到的值会与s2所赋的值保持一致,即“美国”;)*/

s2.country = “美国”;

s1.show();

s2.show();

s3.show();

Student.staticMethod();

}

}

class Student {

String name;

int age;

static String country;

static class InnerClass {

}

public Student(String name, int age) {

super();

this.name = name;

this.age = age;

}

public Student() { //无参构造方法

super();

}

public Student(String name, int age, String country) { //构造方法、快速初始化成员变量

super();

this.name = name;

this.age = age;

Student.country = country;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public void show() { //定义show方法,实现学生信息打印输出

System.out.println(“Student [name=” + name + “, age=” + age + “,country=” + country + “]”);

}

// public String getCountry() {

// return country;

// }

public static String getCountry() {

// System.out.println(this.name);

return country;

}

public static void setCountry(String country) {

Student.country = country;

}

public static void staticMethod() {

System.out.println(“Student.staticMethod()”);

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文章大纲:1.为什么static会有这样的效果?2.static的使用3.static误区4.static面试题 ...
    柠檬乌冬面阅读 5,933评论 3 43
  • static在日常开发过程中不可避免的一个关键字,也是面试中经常被提及的一个基础知识。对static的认识印象中只...
    打不开的回忆阅读 1,318评论 2 50
  • (1)static 关键字用于修饰变量,方法,和代码块; (2)被static修饰的变量或方法不依赖于特定对象,可...
    伊凡的一天阅读 491评论 0 3
  • Java中的 static 关键字主要是用来做内存管理的。被static修饰的成员变量和成员方法独立于该类的任何对...
    mingaqi阅读 2,052评论 0 1
  • 我是谁? 在父母眼里,无论我长多大,我永远都是他们心里最疼爱的孩子。 在亲人眼里,待我如家人一般,我一直都被幸福和...
    夢一場921阅读 325评论 1 3