Java中static关键字的理解

static关键字含义可以理解为静态的。

1. 当其修饰属性时,该属性为整个类公有,所有的对象操作的都是同一个静态属性。所以调用时应该使用类名去调用,而不需要使用对象调用。

用类名去调用static有两层含义:

1. 可以理解为其为整个类公有的内容。

2. 可以理解为不需要创建对象就可以直接使用。

class Student {

private String name;

private String no;

// 此处省略掉getter和setter

public static String school;

public static void main(String[] args) {

Student stu1 = new Student();

stu1.setName("小马哥");

stu1.setNo("1001");

Student.school = "千锋";

Student stu2 = new Student();

Student.school = "千锋教育";

System.out.println(Student.school);

}

}

2. 当其修饰方法时,该方法不需要对象调用,直接使用类名即可调用。

// 只显示代码片段

public static String getSchool() {

return school;

}

// 其他位置调用

System.out.println(Student.getSchool());

注意:在static方法中不能调用普通属性。也不能使用this关键字。因为static方法是使用类名调用的,而使用时不能判断是否创建对象,所以根本不能调用对象所对应的方法或属性,只能调用static的属性或方法。

代码块,是指在类中,直接使用{}中间写一段代码,此代码不需要手动调用,在每次创建对象时会自动调用,甚至会在构造方法之前调用。

public class Student {

private String name;

private String no;

public static String school;

public Student(){

System.out.println("无参构造函数");

}

{

System.out.println("此处是代码块");

}

}

3. 当static修饰代码块时,该代码块为静态代码块,在类加载时调用,仅在第一次加载时调用一次。不需要创建对象。如果创建了对象,调用次序为:先调用static代码块,再调用代码块,最后调用构造方法。

public class Student {

private String name;

private String no;

public static String school;

public Student(){

System.out.println("无参构造函数");

}

{

System.out.println("此处是代码块");

}

static{

System.out.println("此处是静态代码块");

}

}

当有一个父类Person,有一个子类Student,分别都有构造方法,代码块和静态代码块时,创建一个子类对象,调用次序为:

此处是Person静态代码块

此处是Student静态代码块

此处是Person代码块

Person无参构造函数

此处是Student代码块

Student无参构造函数

代码如下:

public class Person {

public Person(){

System.out.println("Person无参构造函数");

}

{

System.out.println("此处是Person代码块");

}

static{

System.out.println("此处是Person静态代码块");

}

}

public class Student extends Person{

public Student(){

System.out.println("Student无参构造函数");

}

{

System.out.println("此处是Student代码块");

}

static{

System.out.println("此处是Student静态代码块");

}

}

总结一句:static其实翻译类的,更容易理解,比如static修饰属性,称为类属性,static修饰方法,称为类方法。

原文地址:https://www.cnblogs.com/qfchen/p/11246008.html